1

I am learning Swift and trying to pull data from local host MySQL database. Following some tutorials I was able to get this:

   func getInfo()  {
    let url = NSURL(string: "http://localhost:8888/service.php")
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithURL(url!) {(data, response, error) in
        var d = NSString(data: data, encoding: NSUTF8StringEncoding)
        var arr = d!.componentsSeparatedByString("<") 
        var dataweneed:NSString = arr[0] as! NSString
        if let data = NSJSONSerialization.JSONObjectWithData(dataweneed.dataUsingEncoding(NSUTF8StringEncoding)!, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSArray {

            self.tableData = data
            println(data)
        }
    }
    task.resume()

This is in the view controller file.

I call the function form the viewDidLoad. I declare a variable tableData:NSArray = [] at the top, and I can see the data via the println(data) inside the function, but if I try to use tableData outside the function, it is empty.

How can I get the data that is inside variable 'data' to be able to use outside the function?

1 Answer 1

1

Reload your tableView when you get data from server this way:

func getInfo()  {
let url = NSURL(string: "http://localhost:8888/service.php")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!) {(data, response, error) in
    var d = NSString(data: data, encoding: NSUTF8StringEncoding)
    var arr = d!.componentsSeparatedByString("<") 
    var dataweneed:NSString = arr[0] as! NSString
    if let data = NSJSONSerialization.JSONObjectWithData(dataweneed.dataUsingEncoding(NSUTF8StringEncoding)!, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSArray {

        self.tableData = data
        println(data)

        // Reload tableView here.
        dispatch_async(dispatch_get_main_queue()) {
            self.tableView.reloadData()
        }
    }
}
task.resume()

Hope this will help.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.