Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Mysql data response and real showing list in table view are different

Hi, nice to meet you! I am quite new to IOS and facing trouble. Please anybody help me.

I am building a searching table view with mysql data. When it runs first, it shows every list in table correctly. But When I type at the searchbar and check the response and simulator, response in Xcode and list in table in simulator is different.

For example, when I type "IFC" at the searchbar, I can find that response on Xcode show information about "IFC". but on table view in simulator shows different list.

Please let me know problem in my code. Kindly check my code as below,

class ClubViewController: UIViewController, UITableViewDataSource, UISearchBarDelegate, UITableViewDelegate {

@IBOutlet weak var mySearchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!

var searchResults = [String]()
var clubName = [String]()
var clubLocation = [String]()
var clubPhoto = [UIImage]()
var clubPhoto_lbl = [String]()
var clubTwomale = [String]()
 var searchClub = " "
var set = ""
 var on = "on"
var urls = [NSURL]()

var male_chart_label: [String]!
var male_chart_num: [Double] = []
var female_chart_label: [String]!
var female_chart_num: [Double] = []


var dataPoints = [String]()
var values = [Double]()



override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.


       doSearch("")

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}




func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return searchResults.count

}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    var myCell = tableView.dequeueReusableCellWithIdentifier("clubCell", forIndexPath: indexPath) as! ClubTableCell

    myCell.name.text = clubName[indexPath.row]
    myCell.location.text = clubLocation[indexPath.row]
    myCell.photo.image = clubPhoto[indexPath.row]
    myCell.ratings.rating = clubRatingFinalArray[indexPath.row]


    return myCell

}


func searchBarSearchButtonClicked(searchBar: UISearchBar)
{
  doSearch(searchBar.text!)

}


func doSearch(searchWord: String)
{

    mySearchBar.endEditing(true)

    let myUrl = NSURL(string: "mysql url")

    let request = NSMutableURLRequest(URL:myUrl!);
    request.HTTPMethod = "POST"

    print("search=\(searchWord)")
    print(set)

      let postString = "search=\(searchWord)&registered=on"

//   let postString = "search=Ifc&registered=on"

    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data:NSData?, response: NSURLResponse?, error:NSError?) -> Void in

        dispatch_async(dispatch_get_main_queue()) {


            if error != nil
            {
                // display an alert message
                self.displayAlertMessage(error!.localizedDescription)
                return
            }

            print("******* response = \(response)")

            // Print out reponse body
            let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("****** response data = \(responseString!)")


            do {
                let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

                self.searchResults.removeAll(keepCapacity: false)
             //   self.tableView.reloadData()

                if let parseJSON = json {

                    if let friends  = parseJSON["friends"] as? [AnyObject]
                    {
                        for friendObj in friends
                        {


                            let fullName = (friendObj["name"] as! String) + " " + (friendObj["location"] as! String)

                           let club_name = friendObj["name"] as! String
                            let club_location = friendObj["location"] as! String
                            let club_photo_lbl = friendObj["image_place"] as! String

                            let club_photo = friendObj["image_place"] as! NSString

                           let reposURL = NSURL(string:  "image-url")

                         if let data = NSData(contentsOfURL: reposURL!)
                            {

                                let image = UIImage(data: data)!
                               self.clubPhoto.append(image)

                            }
                           self.searchResults.append(fullName)
                            //                                self.urls.append(NSURL(string: "images/"+(club_photo as String))!)



                            self.clubName.append(club_name)
                            self.clubLocation.append(club_location)
                            self.clubPhoto_lbl.append(club_photo_lbl)

                       }

                        self.tableView.reloadData()

                    } else if(parseJSON["message"] != nil)
                    {

                        let errorMessage = parseJSON["message"] as? String
                        if(errorMessage != nil)
                        {
                            // display an alert message
                            self.displayAlertMessage(errorMessage!)
                        }
                    }
                }

            } catch {
                print(error);
            }

        }


    })


    task.resume()

}


func displayAlertMessage(userMessage: String)
{
    let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.Alert);
    let okAction =  UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)
    myAlert.addAction(okAction);
    self.presentViewController(myAlert, animated: true, completion: nil)
}

@IBAction func cancelButtonTapped(sender: AnyObject) {
    mySearchBar.text = ""
   mySearchBar.endEditing(true)
}

}