Vahid Vahid - 7 months ago 25
Swift Question

How to Synchronize iOS class object (Swift / iOS 9)

I have a class method, This method will take some time to get data from an http request.

Related part of the method:

do{
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions())
} catch {
print("Cound not serilize")
}
let task = session.dataTaskWithRequest(request) {
data, response, error in
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions()) as? NSDictionary
self.result = json! as? [String : AnyObject]
print(self.result)


It will print correct result from JSON, but in other side the object instance
authGuestAPI
will not:

let authGuestAPI = API(url: apiUrl, params: params, method: "POST")
authGuestAPI.run()
print("RESULT: \(authGuestAPI.result)")


It will print "RESULT: nil"

but If I put
NSThread.sleepForTimeInterval(2)
before
print("RESULT: \(authGuestAPI.result)")
It will print correct json data.

Answer

I use SwiftyJSON and Alamofire to make download method with completionHandler to fix this issue.

func download(completionHandler: (JSON?, NSError?) -> ()) -> (){
    Alamofire.request(.POST, url, parameters: self.params, encoding: ParameterEncoding.URLEncodedInURL , headers: self.header).responseJSON { (result: Response<AnyObject, NSError>) -> Void in

        if result.result.isSuccess {
            self.hasError = false
            self.result = JSON(result.result.value!)

        } else if result.result.isFailure {
            self.errorCode = result.result.error!.code
            self.errorMessage = result.result.error!.localizedDescription
            print(result.result.error?.localizedDescription)
            self.hasError = true
        }

        completionHandler(self.result, result.result.error)
    }

}
Comments