Vahid Vahid - 5 months ago 14x
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:

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]

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

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

It will print "RESULT: nil"

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


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
            self.hasError = true

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