KarthiK Mandava KarthiK Mandava - 6 months ago 22
Swift Question

Unable to perform anything after AsynchronusRequest in Swift

I am working with Swift first time. I am firing Web API as shown below and I am getting data successfully but I am unable to perform any thing in NSURLConnection.sendAsynchronousRequest black. I am printing result after that I have wrote segue perform method and but it not pushing to another ViewController and it stay in same view controller. Thanks in advance.

NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
//SwiftLoader.hide()
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
SwiftLoader.hide()
print("ASynchronous\(jsonResult)")
self.performSegueWithIdentifier("Home", sender: self)
}
self.hideView()
}
catch let error as NSError
{
print(error.localizedDescription)
}
})

Answer

If you want to perform a segue it should perform on main thread , not in a background thread. NSURLConnection.sendAsynchronousRequest run on background thread, so if you want any UI related modification, you should use main thread. so use like this :-

   NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
        //SwiftLoader.hide()
        do {
            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                 SwiftLoader.hide()
                print("ASynchronous\(jsonResult)")
                dispatch_sync(dispatch_get_main_queue(), {
                    self.performSegueWithIdentifier("Home", sender: self)                                          
                })

            }
            self.hideView()
        }
        catch let error as NSError
        {
            print(error.localizedDescription)
        }
    })