如果你看到分支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>
並根據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
}
}
然後,如果你按照這個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引入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遷移過程。
我希望這對你有所幫助。
男人,對不起,對付offtop,但你能幫我步驟添加alamofire到xcode 7 beta 6嗎?我不能這樣做,因爲在「鏈接框架」中,我沒有看到alamofire。 thx) – SwiftStudier
您需要爲swift 2分支添加窗格,您的Alamofire的Podfile應該如下所示:pod'Alamofire',::git =>'https://github.com/Alamofire/Alamofire.git',:分支=>'swift-2.0' – mattgabor