2015-08-28 86 views
6

我想在Alamofire中發出一個POST請求來返回一個JSON對象。此代碼工作在斯威夫特1,但在迅疾2我得到這個無效的參數問題:Alamofire POST請求與斯威夫特2

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

這似乎是錯誤的參數被刪除,但我現在用的是函數內部的誤差參數來檢查錯誤,所以我將如何做到這一點沒有錯誤參數?

這裏是我的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) 
       } 
     } 
+1

男人,對不起,對付offtop,但你能幫我步驟添加alamofire到xcode 7 beta 6嗎?我不能這樣做,因爲在「鏈接框架」中,我沒有看到alamofire。 thx) – SwiftStudier

+0

您需要爲swift 2分支添加窗格,您的Alamofire的Podfile應該如下所示:pod'Alamofire',::git =>'https://github.com/Alamofire/Alamofire.git',:分支=>'swift-2.0' – mattgabor

回答

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 
    ) 
} 

現在它返回一個enumResult<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遷移過程。

我希望這對你有所幫助。

+0

謝謝,你有鏈接到你指的Swift 2文檔嗎? – mattgabor

+0

不客氣。如果您將Github中的分支更改爲'Swift2.0',您可以在下面看到更新的文檔。但如果您想了解更多信息,則必須在源代碼中介紹自己,這不難遵循。 –

+0

@VictorSigler在' - > Self'顯示錯誤。請幫幫我! – iRiziya

2

您是否嘗試過在.responseJSON使用三個參數,將圍繞要記錄錯誤的領域try catch塊,檢查this link如果您需要幫助用swift 2 try catch