NSURLSession.sharedSession()。dataTaskWithRequest(请求)最后执行

时间:2016-07-28 14:22:38

标签: ios swift nsurlsession health-kit

我遇到NSURLSession.sharedSession().dataTaskWithRequest(request)的问题。我想针对某些API验证我的应用程序,如果验证成功,那么应用程序将让用户授权运行状况工具包,最后从那里获取一些数据。

我在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的情况下授权保健套件的步骤。最后,当卫生工具包获得批准后,它会返回并授权Apigee。

知道为什么会发生这种情况? 任何提示都将不胜感激!

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

NSURLSession.sharedSession()。dataTaskWithRequest()在另一个线程中执行。这样主应用程序线程就不会挂起并等待请求完成。如果您希望在异步任务完成后运行代码块,我建议您使用完成块。

答案 2 :(得分:1)

你需要使用闭包因为api以async方式调用工作所以首先要改变你的函数定义

func authorizeApigee(completion: (Int) -> ()){
    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
        {
            completion(0)
            print("error=\(error)")
            return
        }
        // Print out response string
        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("responseString = \(responseString)")
        completion(1)
    }
    task.resume()
}

现在像这样调用你的函数

self.authorizeApigee() { (result) -> () in
     if result == 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!")
      }  
}