KeykoYume KeykoYume - 4 months ago 4
iOS Question

NSURLSession.sharedSession().dataTaskWithRequest(request) being executed last

I'm having a problem with

NSURLSession.sharedSession().dataTaskWithRequest(request)
. I want to authenticate my app against some API and if the authentication is successful then the app will let the user to authorise health kit and finally fetch some data from there.

I have this in my
viewDidLoad()


print ("AUTHORIZING APIGEE!!!")
authorizeApigee()
if (self.errorApigee == 0) {
print ("APIGEE AUTHORIZED!")
// We cannot access the user's HealthKit data without specific permission.
print ("AUTHORIZING HEALTHKIT!!")
getHealthKitPermission()
print ("HEALTHKIT AUTORIZED!")
} else {
print ("APIGEE UNAUTHORIZED!")
}


and this is the authorising function:

// Authenticating app with Apigee Health APIx
func authorizeApigee(){
// Send HTTP GET Request


let scriptUrl = "https://fhirsandbox-prod.apigee.net/oauth/v2"
let urlWithParams = scriptUrl + "/accesstoken?grant_type=client_credentials"
let myUrl = NSURL(string: urlWithParams);

let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST"

// Add Basic Authorization

let username = "****"
let password = "****"
let loginString = NSString(format: "%@:%@", username, password)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
request.setValue(base64LoginString, forHTTPHeaderField: "Authorization")

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in

// Check for error
if error != nil
{
self.errorApigee = 1
print("error=\(error)")
return
}

// Print out response string
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
}


The problem is that even though
authorizeApigee()
is called, the app stops at
NSURLSession.sharedSession().dataTaskWithRequest(request)
, goes out of the function, obviously
errorApigee
variable is not updated and therefore it goes to the next step of authorising health kit without authorising Apigee. Finally when health kit was authorised it goes back and authorises Apigee.

Any idea why this might happen at all?
Any tip would be greatly appreciated!

Answer

This is simple example how to use completion :

func authorizeApigee(completion: (auth: Bool) -> Void) {
           // Send HTTP GET Request
    let scriptUrl = "https://fhirsandbox-prod.apigee.net/oauth/v2"
    let urlWithParams = scriptUrl + "/accesstoken?grant_type=client_credentials"
    let myUrl = NSURL(string: urlWithParams);

    let request = NSMutableURLRequest(URL:myUrl!);
    request.HTTPMethod = "POST"

    // Add Basic Authorization

    let username = "****"
    let password = "****"
    let loginString = NSString(format: "%@:%@", username, password)
    let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
    let base64LoginString = loginData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
    request.setValue(base64LoginString, forHTTPHeaderField: "Authorization")

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        // Check for error
        if error != nil
        {
            self.errorApigee = 1
            print("error=\(error)")
             completion(auth: false)
        }

        // Print out response string
        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("responseString = \(responseString)")
         completion(auth: true)
    }
    task.resume()
}

And how to use :

 self.authorizeApigee { (auth) -> Void in
        if (auth) {
           getHealthKitPermission()
        } else {
          //print errors
        }
    }