如何在调用AlamoFire的POST函数时拥有一个完成处理程序?

时间:2016-07-20 23:40:01

标签: ios swift alamofire

我熟悉通常在.response或之后使用alamofire功能。像this post中的responseJSON或类似的那样:

func checkInLocation (accessToken: String, id: Int, latitude: Double, radius: Double, longitude: Double, completionHandler: String) {

  let headers = [

    "Authorization": "bearer \(accessToken)",
    "Cache-Control": "no-cache",
    "Content-Type": "application/json"
  ]

  let parameters: [String: AnyObject] = [
    "id" : id,
    "latitude": latitude,
    "radius": radius,
    "longitude":longitude,
    "languageCulture": "en"
  ]

  Alamofire.request(.POST, "\(baseApiUrl)members/\(id)/checkin", parameters: parameters, encoding: .JSON, headers: headers)
    .responseJSON(completionHandler: { response in

      if((response.result.value) != nil) {

        let swiftyJsonVar = JSON(response.result.value!)

        print("This is the checkin response:\(swiftyJsonVar)")
      }
  })
}

我试图从调用函数中获取它,如下所示:

   checkInLocation(userInfo.sharedInstance.getAccessToken(), id: userInfo.sharedInstance.getMemberID()!, latitude: currentUserLatitude!, radius: 0.3, longitude: currentUserLongitude!, completionHandler: {

      //get JSON response data here

      })

1 个答案:

答案 0 :(得分:1)

您可以参考下面的内容更新您的代码(查看说明中的注释)

// 1. specify the completion and variables/ data you want to pass. can be more than one with different types (depends on your need)
func checkInLocation (accessToken: String, id: Int, latitude: Double, radius: Double, longitude: Double, completionHandler: (json: JSON) -> Void) {

    let headers = [

        "Authorization": "bearer \(accessToken)",
        "Cache-Control": "no-cache",
        "Content-Type": "application/json"
    ]

    let parameters: [String: AnyObject] = [
        "id" : id,
        "latitude": latitude,
        "radius": radius,
        "longitude":longitude,
        "languageCulture": "en"
    ]

    Alamofire.request(.POST, "\(baseApiUrl)members/\(id)/checkin", parameters: parameters, encoding: .JSON, headers: headers)
        .responseJSON(completionHandler: { response in

            if((response.result.value) != nil) {

                let swiftyJsonVar = JSON(response.result.value!)

                // 2. now pass your variable / result to completion handler
                completionHandler(json: swiftyJsonVar)

                print("This is the checkin response:\(swiftyJsonVar)")
            }
        })
}

并调用函数

checkInLocation(String, id: Int, latitude: Double, radius: Double, longitude: Double) { (json) in
   //
}