0

In this code, request.getStatusCode() and request.getIsConnected() both execute before the code inside the task block is executed

i.e. dataTask.resume() doesn't execute until after any subsequent code is executed, be it code in the same function, class, or separate class.

I've tried putting the function call in the main queue (serial), a global queue (concurrent), a manual serial queue, a manual concurrent queue and an NSOperationQueue, all followed by a a while loop to wait until the closure completes.

while isDoingSomething {
    NSThread.sleepForTimeInterval(0.0)
}

loop.

I've left any GCDs or operations out of this code to avoid the clutter of each queue scenario I've tried.

ViewController.swift

import Cocoa
class ViewController: NSViewController {
    .
    .
    .
    func login(username username: String, password: String) {
        let url = "https://www.awebsite.com/login"
        let URL = NSURL(string: url)
        let method = "POST"
        let params = "username=\(username)&password=\(password)"
        vis = URLVisitor(URL: URL!, params: params, method: method, jsonParams: [:])
        vis.execute()
        cookies = vis.getCookies()
        let contentsOfURL = vis.getContentsOfURL()
    }
    .
    .
    .
}

URLVisitor.swift

import Cocoa
let queue = NSOperationQueue

class URLVisitor: NSOperation {
    .
    .
    .

    func execute() {
        let request = Request(URL: URL!, params: params, method: method, jsonParams: jsonParams)
        if !self.cookies.isEmpty {
            request._setCookies(self.cookies)
        }

        request._setAuthorizationHeader(self.authorizationHeader)
        request.sendRequest()

        self.statusCode = request.getStatusCode()
        self.isConnected = request.getIsConnected()
    }
    .
    .
    .

}

Request.swift

import Cocoa
class Request: NSOperation {
    .
    .
    .

    func sendRequest() { 
        let session = NSURLSession.sharedSession()
        let request = NSMutableURLRequest(URL: URL)
        request.HTTPMethod = method

        // send jsonParams or params
        if jsonParams.count != 0 {
            do {
                let jsonData = try NSJSONSerialization.dataWithJSONObject(jsonParams, options: .PrettyPrinted)

                request.setValue("aplication/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
                request.HTTPBody = jsonData
            } catch {   
        }
    } else {
        request.HTTPBody = self.params.dataUsingEncoding(NSUTF8StringEncoding)
    }
    let task = session.dataTaskWithRequest(request) {
        (data, response, error) in

    NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookies(self.cookies, forURL: self.URL, mainDocumentURL: nil)
        if data != nil {
            self.data = data!
            do {
                let responseHeaders = response as! NSHTTPURLResponse
                self.statusCode = responseHeaders.statusCode

                switch self.statusCode {
                    case 200:
                        print("200: OK. getting contentsOfURL and cookies")
                        self.contentsOfURL = try NSString(contentsOfURL: self.URL, encoding: NSUTF8StringEncoding)
                        self.cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookiesForURL(self.URL)!

                    case 400:
                        print("400: page not found on web")

                    case 404:
                        print("404: page not found on server")

                    case 407:
                        print("407: failed authenticate proxy credentials")

                    default:
                        print("unable to get statusCode")
                }
            } catch {

            }
        } else {
            print("\(self.statusCode): unable to get response ")
        }   
        NSThread.sleepForTimeInterval(1.0)
    }
    task.resume()
}
2
  • Waiting for completion of an asynchronous task using while and sleep is horrible. Learn to understand the asynchronous behavior of the tasks of NSURLSession. For example put both functions into the completion block.
    – vadian
    Jul 1, 2016 at 20:54
  • Thank you. Believe me; I know a while loop is horrible. That's why I'm looking for help. But the return value of the functions are needed by the VC class. Putting them in the task closure wouldn't make sense to me because those variables are already present in the class that the task closure is in (URLVisitor). What am I missing? Can you recommend a good tutorial that explains this better? Jul 1, 2016 at 22:37

1 Answer 1

1

The proper way to do this is to add a completion handler

func sendRequest(completion: () -> Void) {
    // ...
    let task = session.dataTaskWithRequest(request) {
        // ...

        completion()
    }
    task.resume()
}

Usage:

let r = Request()
r.sendRequest {
    // It's done, do something
}

If you insist on blocking the thread (I hope it's not the main thread), use a semaphore. But remember to signal semaphore whether the request succeeded or failed. I've seen far too many code that forgot to signal the semaphore when the request fail so the app just hung up.

func sendRequest() {
    let semaphore = dispatch_semaphore_create(0)

    let task = session.dataTaskWithRequest(request) {
        // ...
        dispatch_semaphore_signal(semaphore)
    }
    task.resume()
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.