Alamofire完成处理程序未被调用

时间:2016-06-20 20:44:16

标签: ios iphone swift alamofire completionhandler

我正在尝试在AlamoFire完成处理程序中调用prepareForSegue方法,但它没有被调用。这是我的代码:

func loginMember (username: String, password: String, completionHandler: (String?, ErrorType?) -> ()) {

  let headers = [
    "Cache-Control": "no-cache",
    "Content-Type": "application/json"
  ]

  let parameters: [String: AnyObject] = [

    "grant_type" : "password",
    "username" : username,
    "password" : password,

  ]

      Alamofire.request(.POST, "\(baseURL)/oauth2/token", parameters: parameters, encoding: .JSON, headers: headers)
        .validate()
        .responseJSON { response in
          switch response.result {
          case .Success:

            guard let value = response.result.value else {
              completionHandler(nil, response.result.error)
              return
            }

            let swiftyJsonVar = JSON(value)

              accessToken = swiftyJsonVar["access_token"].stringValue

            print("This is the login response:\(swiftyJsonVar)")

          case .Failure(let error):
           print("Sorry there was an error: \(error)")

            return
          }

      }

    }

这就是调用时的样子:

loginMember(username, password: password, completionHandler: { error in

  dispatch_async(dispatch_get_main_queue()) {
  self.performSegueWithIdentifier("loginToHomeSegue", sender: self)
  }
  }
)

关于为什么没有调用performSegueWithIdentifier的任何想法?

1 个答案:

答案 0 :(得分:1)

您只是在输入保护声明的情况下调用完成处理程序。您需要为获取访问令牌和错误案例的情况添加调用。

Alamofire.request(.POST, "\(baseURL)/oauth2/token", parameters: parameters, encoding: .JSON, headers: headers)
            .validate()
            .responseJSON { response in
                switch response.result {
                case .Success:

                    guard let value = response.result.value else {
                        completionHandler(nil, response.result.error)
                        return
                    }

                    let swiftyJsonVar = JSON(value)

                    accessToken = swiftyJsonVar["access_token"].stringValue

                    print("This is the login response:\(swiftyJsonVar)")

                    // Got the token, call handler
                    completonHandler(accessToken, nil)

                case .Failure(let error):
                    print("Sorry there was an error: \(error)")

                    // Got an error, call handler
                    completionHandler(nil, error)

                    return
                }
        }