Search code examples
iosswift2nsurlsessionnsurlsessiondatatask

Function completes before NSURLSession - dataTaskWithRequest completed


I have the following method called under ViewDidLoad(). I understand that session.dataTaskWithRequest automatically runs in background thread. And because of the same, the code following this method in ViewDidLoad() does not wait for this process to complete and starts executing.

Is there any way that I can ensure that the background thread is completed before other methods are executed?

    func getCoordinatesFromServer() {
        let request = NSMutableURLRequest(URL: NSURL(string: constants.urlName.loadData)!)
        request.HTTPMethod = "POST"
        request.addValue("multipart/form-data", forHTTPHeaderField: "Accept")
        request.setValue("keep-Alive", forHTTPHeaderField: "Connection")
        request.HTTPBody = (constants.requestTag.getCoordinates).data

        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithRequest(request, completionHandler: {(data, response ,error ) in
            if let response = response {
                let httpResponse = response as! NSHTTPURLResponse

                print("response code = \(httpResponse.statusCode)")
                if (httpResponse.statusCode == 200) {
                    dispatch_async(dispatch_get_main_queue(), {
                        let decodedData = NSData(base64EncodedData: data!, options: NSDataBase64DecodingOptions([]))
                        let jsonText = NSString(data: decodedData!, encoding: NSASCIIStringEncoding) as! String
                        do {
                        let json = try NSJSONSerialization.JSONObjectWithData(jsonText.data, options: NSJSONReadingOptions.init(rawValue: 0))
                        self.parseJsonData(json["Datalist"] as! NSArray)
                        } catch {
                        print("Error:\n \(error)")
                        }
                    })
                }
            }
        })
        task.resume()
    }

Regards,


Solution

  • if I understand your question, you can solve this problem at this way For example:

    class func ConnectedToNetwork(completionHandler: ((Status: Bool) -> Void))
        {
        let url = NSURL(string: "http://google.com")
        let request = NSMutableURLRequest(URL: url!)
        request.HTTPMethod =  "HEAD"
        request.timeoutInterval = 0.2
           let task = NSURLSession.sharedSession().dataTaskWithURL(url!)    {(data,response, error) in
                let httpResponse = response as! NSHTTPURLResponse
                    if httpResponse.statusCode == 200
                    {   completionHandler(Status: true)
                        return
                    }
            }
            task.resume()
        }
    

    and then, you can work with this

    Checks.ConnectedToNetwork({ Status in dispatch_async(dispatch_get_main_queue())
            {
                if Status == true
                {
                    //do what you want
                 }
    });