SwiftyJD
SwiftyJD

Reputation: 5441

Alamofire completion handler not being called

I'm currently trying to call a prepareForSegue method in an AlamoFire completion handler but it's not being called. Here is my code:

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
          }

      }

    }

This is what it looks like when called:

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

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

Any ideas as to why the performSegueWithIdentifier isn't being called?

Upvotes: 1

Views: 1666

Answers (1)

dan
dan

Reputation: 9825

You're only calling your completion handler in the case where you enter your guard statement. You need to add calls for the case where you get your access token and your error case.

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
                }
        }

Upvotes: 1

Related Questions