使用Swift 2的Alamofire POST请求

mat*_*bor 6 post json swift alamofire swift2

我正在尝试在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)
Run Code Online (Sandbox Code Playgroud)

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

这是我的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)
                }
        }
Run Code Online (Sandbox Code Playgroud)

Vic*_*ler 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
    )
}
Run Code Online (Sandbox Code Playgroud)

现在它返回一个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.
Run Code Online (Sandbox Code Playgroud)

它有一个名为的财产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
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,如果您在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")
}
Run Code Online (Sandbox Code Playgroud)

更新:

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>
}
Run Code Online (Sandbox Code Playgroud)

所以你可以像下面那样调用它:

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

您可以在Alamofire 3.0迁移指南中阅读有关迁移过程的更多信息.

我希望这对你有帮助.