我对NSURLSession.sharedSession().dataTaskWithRequest(request)有问题。我想根据一些API对我的应用程序进行身份验证,如果身份验证成功,那么应用程序将允许用户授权health kit,并最终从那里获取一些数据。
我的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!")
}

这是授权功能:
// 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()
    }

问题是,即使调用了authorizeApigee(),应用程序也会停止在NSURLSession.sharedSession().dataTaskWithRequest(request),退出功能,显然errorApigee变量没有更新,因此它会在未经Apigee授权的情况下进入授权健康工具包的下一步。最后,当健康工具包被授权时,它会返回并授权给阿皮吉。
你知道为什么会这样吗?
任何小费都将不胜感激!

最佳答案

这是如何使用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()
}

以及如何使用:
 self.authorizeApigee { (auth) -> Void in
        if (auth) {
           getHealthKitPermission()
        } else {
          //print errors
        }
    }

10-08 08:07