I'm developing an application what's based on JSON objects requested from specified URL but sometimes (not every time) I get no result
Gonna show some code snippets that can help determining this simple (?) problem
I have an array called "Data" (var Data:[String] = []
) in my class MyTestClass
and the following function:
func loadData(onComplete: ([String]) -> ()) {
// Declaring a local array
var Local:[String] = []
// Preparing JSON request
let address = "<URL goes here>"
let url = NSURL(string: address)
let request = NSURLRequest(URL: url!)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { (data, response, error) in
if (data?.length > 0 && error == nil) {
let responseData = data as NSData!
if responseData == nil {
// Presenting some alert
} else {
let jsonObject: AnyObject? = try? NSJSONSerialization.JSONObjectWithData(responseData!, options: NSJSONReadingOptions.MutableContainers)
if jsonObject == nil {
// Presenting some alert
} else {
let json: NSArray = jsonObject as! NSArray
for (var i = 0; i < json.count; i++) {
if let obj = json[i] as? NSDictionary {
if let m = obj["m"] as? String {
if m != "Unknown" {
Local.append(m)
}
}
}
}
onComplete(Local)
}
}
} else if error != nil {
NSLog("Error: %@", error!)
}
}
// Starting task
task.resume()
}
In viewDidLoad() I'm doing the following:
// Loading data
loadData { (d) in
for dat in d {
self.Data.append(dat)
}
}
I'm using this solution (the functions are 100% the same [CTRL+C / CTRL+V]) in every of my ViewControllers, my hierarchy is the following: Table1 -> Table2 -> Table3
Table1 works fine, has no problem, displays the results every time fine, Table2 works most of the time (sometimes very rarely displays no result) but Table3 goes crazy ~80% of the time.
I'm getting mad because of this thing happening to me, before iOS 9 I used synchronous calls and had no problems because it's a small application, but now I don't even know how to make it work with this session.dataTaskWithRequest...
thing.