使用Swift 2的Alamofire POST请求

时间:2015-08-28 18:35:43

标签: json swift post swift2 alamofire

我正在尝试在Alamofire中发出POST请求以返回JSON对象。这个代码在Swift 1中有效,但是在swift 2中我得到了这个无效的参数问题:

Tuple types '(NSURLRequest?, NSHTTPURLResponse?, Result<AnyObject>)' (aka '(Optional<NSURLRequest>, Optional<NSHTTPURLResponse>, Result<AnyObject>)') and '(_, _, _, _)' have a different number of elements (3 vs. 4)

似乎错误参数已被删除,但我在函数内部使用error参数来检查错误,那么如果没有错误参数,我该如何做呢?

这是我的POST请求代码:

            let response = Alamofire.request(.POST, urlPath, parameters: parameters, encoding: .URL)
            .responseJSON { (request, response, data, error) in
                if let anError = error
                {
                    // got an error in getting the data, need to handle it
                    print("error calling POST on /posts")
                    print(error)
                }
                else if let data: AnyObject = data
                {
                    // handle the results as JSON, without a bunch of nested if loops
                    let post = JSON(data)
                    // to make sure it posted, print the results
                    print("The post is: " + post.description)
                }
        }

2 个答案:

答案 0 :(得分:9)

如果您在分支Swift2.0中看到文档,您可以看到responseJSON函数已更改,如错误所示,它现在有三个参数,但您也可以捕获错误,让我们看一下看:

public func responseJSON(
    options options: NSJSONReadingOptions = .AllowFragments,
    completionHandler: (NSURLRequest?, NSHTTPURLResponse?, Result<AnyObject>) -> Void)
    -> Self
{
    return response(
        responseSerializer: Request.JSONResponseSerializer(options: options),
        completionHandler: completionHandler
    )
}

现在它返回enum Result<AnyObject>并根据文档:

Used to represent whether a request was successful or encountered an error.

- Success: The request and all post processing operations were successful resulting in the serialization of the 
           provided associated value.
- Failure: The request encountered an error resulting in a failure. The associated values are the original data 
           provided by the server as well as the error that caused the failure.

它包含一个名为error的属性,其中包含以下文档:

/// Returns the associated error value if the result is a failure, `nil` otherwise.
public var error: ErrorType? {
    switch self {
    case .Success:
        return nil
    case .Failure(_, let error):
        return error
    }
}

然后,如果您在Alamofire中关注此测试用例,您可以看到如何正确获取错误:

func testThatResponseJSONReturnsSuccessResultWithValidJSON() {
    // Given
    let URLString = "https://httpbin.org/get"
    let expectation = expectationWithDescription("request should succeed")

    var request: NSURLRequest?
    var response: NSHTTPURLResponse?
    var result: Result<AnyObject>!

    // When
    Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
        .responseJSON { responseRequest, responseResponse, responseResult in
            request = responseRequest
            response = responseResponse
            result = responseResult

            expectation.fulfill()
        }

    waitForExpectationsWithTimeout(defaultTimeout, handler: nil)

    // Then
    XCTAssertNotNil(request, "request should not be nil")
    XCTAssertNotNil(response, "response should not be nil")
    XCTAssertTrue(result.isSuccess, "result should be success")
    XCTAssertNotNil(result.value, "result value should not be nil")
    XCTAssertNil(result.data, "result data should be nil")
    XCTAssertTrue(result.error == nil, "result error should be nil")
}
  

<强>更新

Alamofire 3.0.0引入了Response结构。所有响应序列化程序(response除外)都返回通用Response结构。

public struct Response<Value, Error: ErrorType> {
   /// The URL request sent to the server.
   public let request: NSURLRequest?

   /// The server's response to the URL request.
   public let response: NSHTTPURLResponse?

   /// The data returned by the server.
   public let data: NSData?

   /// The result of response serialization.
   public let result: Result<Value, Error>
}

所以你可以按照以下方式调用它:

Alamofire.request(.GET, "http://httpbin.org/get")
     .responseJSON { response in
         debugPrint(response)
}

您可以在Alamofire 3.0 Migration Guide

中详细了解迁移过程

我希望这对你有所帮助。

答案 1 :(得分:2)

您是否尝试在.responseJSON中使用三个参数并在想要错误记录的区域周围插入try catch块,如果您需要有关swift 2 try catchs的帮助,请查看this link