2016-10-30 35 views
0

我創建了簡單的項目來檢查像RxAlamofire和AlamofireObjectMapper這樣的庫。我有簡單的ApiService與一個端點,其中PHP腳本正常工作,並返回JSON。我想打電話給recipeURL,我用flatMap運營商得到迴應,並提供給Mapper我應該得到Recipe對象。我該如何做到這一點?Swift 3,RxAlamofire和映射到自定義對象

或者有其他方法嗎?

class ApiService: ApiDelegate{ 
    let recipeURL = "http://example.com/test/info.php" 

    func getRecipeDetails() -> Observable<Recipe> { 
     return request(.get, recipeURL) 
      .subscribeOn(MainScheduler.asyncInstance) 
      .observeOn(MainScheduler.instance) 
      .flatMap({ request -> Observable<Recipe> in 
       let json = ""//request.??????????? How to get JSON response? 
       guard let recipe: Recipe = Mapper<Recipe>().map(JSONObject: json) else { 
        return Observable.error(ApiError(message: "ObjectMapper can't mapping", code: 422)) 
       } 
      return Observable.just(recipe) 
     }) 
    } 
} 

回答

4

RxAlamofire的自述,這似乎是一個方法json(_:_:)在庫中存在。

通常,您寧願使用map而不是flatMap將返回的數據轉換爲另一種格式。如果您需要訂閱新的observable(例如,使用第一個請求的部分結果執行第二個請求),那麼flatMap將非常有用。

return json(.get, recipeURL) 
    .map { json -> Recipe in 
    guard let recipe = Mapper<Recipe>().map(JSONObject: json) else { 
     throw ApiError(message: "ObjectMapper can't mapping", code: 422) 
    } 
    return recipe 
    } 
+0

ok Thx。我會檢查 – Michael

+0

它工作thx;) – Michael

相關問題