简体   繁体   English

使用Swift 2的Alamofire POST请求

[英]Alamofire POST request with Swift 2

I am trying to make a POST request in Alamofire to return a JSON object. 我正在尝试在Alamofire中发出POST请求以返回JSON对象。 This code worked in Swift 1, but in swift 2 I get this invalid parameter issue: 这段代码在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)

It seems like the error parameter was removed, but I am using the error parameter inside the function to check for errors, so how would I do that without an error param? 似乎错误参数已被删除,但我在函数内部使用错误参数来检查错误,那么如果没有错误参数我该如何做呢?

Here's my code for the POST request: 这是我的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)
                }
        }

If you see the documentation in the branch Swift2.0 you can see that the responseJSON function has changed as the error says, it have now three parameters but you can catch the error too, lets take a look: 如果您在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
    )
}

Now it returns an enum Result<AnyObject> and according to the doc : 现在它返回一个enum Result<AnyObject>并根据doc:

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.

And it have inside an property entitled error , with the following doc: 它有一个名为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
    }
}

Then if you follow this test case inside Alamofire you can see how to get the error properly: 然后,如果您在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")
}

UPDATE : 更新

Alamofire 3.0.0 introduces a Response struct. Alamofire 3.0.0引入了一个Response结构。 All response serializers (with the exception of response ) return a generic Response struct. 所有响应串行(有例外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>
}

So you can call it like the following way: 所以你可以像下面那样调用它:

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

You can read more about the migration process in the Alamofire 3.0 Migration Guide . 您可以在Alamofire 3.0迁移指南中阅读有关迁移过程的更多信息。

I hope this help you. 我希望这对你有帮助。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM