Swift 2.0 Alamofire完成处理程序返回Json

时间:2016-02-20 19:55:54

标签: ios json swift alamofire swifty-json

我的目标是创建一个简单的函数,我传入一个url并返回JSON。我环顾四周,发现了Alamofire实现完成处理程序的小例子。

我也在使用Swifty Json帮助解析它。

如何将此处的内容转换为返回Json的函数。

func request() {
    Alamofire.request(.GET, API_END_POINT)
    .responseJSON {
        response in

        // swiftyJsonVar is what I would like this function to return.
        let swiftyJsonVar = JSON(response.result.value!)
    }
}

1 个答案:

答案 0 :(得分:9)

Swift 3 + Alamofire 4 +

 // Call function
    myFunction("bodrum") { response in
      print(response["yourParameter"].stringValue)
    }

    // POST
    func myFunction(_ cityName:String, completion: @escaping (JSON) -> ()) {

      let token = "token"
      let parameters = ["city" : cityName]
      let headers = ["Authorization": "token"]
      let url = URL(string: "url")!
      let reqUrl = URLRequest(url: url)

      Alamofire.request(reqUrl, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: headers)
        .validate()
        .responseJSON { response in
          switch response.result {
          case .Success:
            let jsonData = JSON(data: response.data!)
            completion(jsonData)
          case .Failure(let error):
            MExceptionManager.handleNetworkErrors(error)
            completion(JSON(data: NSData()))
          }
      }
    }

Swift 2 Alamofire 3 +

// POST
func myFunction(cityName:String, completion : (JSON) -> ()) {
  Alamofire.request(.POST, "url", parameters: ["city" : cityName], encoding: ParameterEncoding.JSON, headers: ["Authorization": "token"])
    .validate()
    .responseJSON { response in
      switch response.result {
      case .Success:
        let jsonData = JSON(data: response.data!)
        completion(jsonData)
      case .Failure(let error):
        MExceptionManager.handleNetworkErrors(error)
        completion(JSON(data: NSData()))
      }
  }
}

// GET
func myFunction(cityName:String, completion : (JSON) -> ()) {
  Alamofire.request(.GET, "url", parameters: ["param1" : cityName], headers: ["Authorization": "token"])
    .validate()
    .responseJSON { response in
      switch response.result {
      case .Success:
        let jsonData = JSON(data: response.data!)
        completion(jsonData)
      case .Failure(let error):
        MExceptionManager.handleNetworkErrors(error)
        completion(JSON(data: NSData()))
      }
  }
}

// Call function
myFunction("bodrum") { response in
  print(response["yourParameter"].stringValue)
}