2015-08-28 19 views
6

Bir JSON nesnesini döndürmek için Alamofire'da bir POST isteği oluşturmaya çalışıyorum. Bu kod Swift 1 çalışmış, ancak swift 2'de bu geçersiz parametre sorunu olsun:Swift 2 ile Alamofire POST isteği

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

Bu hata parametresi kaldırılmış gibi görünüyor, ama ben, hatalarını kontrol etmek işlevi içinde hata parametresini kullanıyorum Bir hata param olmadan bunu nasıl yaparım?

İşte POST isteği için benim kod: Yardıma ihtiyacınız varsa

  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

adam, özür dilerim, ama xcode 7 beta 6 içine alamofire eklemek için adımlar ile bana yardımcı olabilir misiniz? Bunu daha önce olduğu gibi yapamam çünkü "bağlantılı çerçevede" alamofire görmüyorum. thx) – SwiftStudier

+0

Hızlı 2 dalı için bölmeyi eklemeniz gerekiyor, Alamofire için Podfile dosyanız şu şekilde görünmelidir: pod 'Alamofire',: git => 'https://github.com/Alamofire/Alamofire.git',: branch => 'swift-2.0' – mattgabor

cevap

9

Eğer responseJSON fonksiyon hatası söylediği gibi değiştiğini görebilirsiniz Swift2.0 dalında belgelerine görürseniz ile, şimdi üç parametre var ama çok hatayı yakalamak, bir göz atalım:

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

Şimdi bir enumResult<AnyObject> ve döner doc göre:

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. 

Ve şu doc ​​ile error başlıklı bir özelliği içinde vardır: Sonra

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

bunu izlerseniz Alamofire içindeki test durumu, hatayı doğru şekilde nasıl alacağınızı görebilirsiniz:

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

GÜNCELLEME:

Alamofire 3.0.0 Bir Response yapı tanıtır. Tüm yanıt serileştiricileri (response hariç), genel Response yapısını döndürür.

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

Yani şu yol gibi diyebilirsiniz:

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

Sen Alamofire 3.0 Migration Guide yılında göç süreci hakkında daha fazla bilgi bulabilirsiniz.

Umarım bu size yardımcı olur.

+0

Teşekkürler, atıfta bulunduğunuz Swift 2 dokümanı bağlantınız var mı? – mattgabor

+0

Rica ederim. Github'daki şubeyi "Swift2.0" olarak değiştirirseniz, aşağıdaki güncellenmiş belgeleri görebilirsiniz. Ama biraz daha fazlasını bilmek istiyorsanız, kendinizi kaynak kodunda tanıtmanız gerekiyor, takip etmek zor değil. –

+0

@VictorSigler '-> Self''te hata gösteriliyor. Lütfen bana yardım et! – iRiziya

2

Eğer .responseJSON üç parametreleri kullanarak ve hata günlüğü istediğiniz alanların etrafında bir deneyin catch bloğu yerleştirirken denediniz, this link kontrol hızlı 2 deneyin fiksatörleri

İlgili konular