Murat Ekici Murat Ekici - 1 year ago 269
JSON Question

NSURLSession.sharedSession().dataTaskWithRequest runs slow in function

My problem arises when I want to populate data from my mysql database into a class object. I am trying to return an array of objects and it returns

and then it fills itself somehow. How can I make it fill before returning the blank array?

Here is my code and a screenshot of code output

import Foundation

class Research
var mainResearchImageURL:String = ""
var userProfileImageURL:String = ""
var caption:String = ""
var shortDescription:String = ""

init(mainResearchImageURL :String, userProfileImageURL:String, caption:String, shortDescription:String)

self.mainResearchImageURL = mainResearchImageURL
self.userProfileImageURL = userProfileImageURL
self.caption = caption
self.shortDescription = shortDescription

class func downloadAllResearches()->[Research]
var researches = [Research]()
let urlString = "http://localhost/test/index.php"
let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
request.HTTPMethod = "POST"
let postString = "action=listresearches"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {data, response, error in
if (error == nil) {

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

var counter:Int = 0;
for line in json!{
let researchData = line as! NSDictionary
let researchLineFromData = Research(mainResearchImageURL: researchData["research_mainImageURL"] as! String, userProfileImageURL: researchData["research_creatorProfileImageURL"] as! String, caption: researchData["research_caption"] as! String, shortDescription: researchData["research_shortDescription"] as! String)
researches.append(researchLineFromData) //researches bir dizi ve elemanları Research türünde bir sınıftan oluşuyor.

counter += 1
print ("counter value \(counter)")
print("array count in loop is = \(researches.count)")
}catch let error as NSError{
} else {

print("array count in return is = \(researches.count)")
return researches

And this is the output:

enter image description here

Answer Source

add this on you completionHandler ( it works if you update a view)

dispatch_async(dispatch_get_main_queue(), {
    if (error == nil) { ...... }

Advice 1:

return the task and use a completion param in your method, you can cancel the task if it's too slow.

Advice 2 : Use alamofire and swiftyJson framework