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()
}
while
andsleep
is horrible. Learn to understand the asynchronous behavior of thetasks
ofNSURLSession.
For example put both functions into the completion block.