2016-10-30 2 views
0

RxAlamofireやAlamofireObjectMapperのようなライブラリをチェックする簡単なプロジェクトを作成しました。私は単純にApiServiceと1つのエンドポイントがあり、適切に動作する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のreadmeファイルから、方法json(_:_:)がライブラリ内に存在するようです。

通常は、flatMapの代わりにmapを使用して、返されたデータを別の形式に変換します。 flatMapは、新しい観測値を登録する必要がある場合(たとえば、最初の観測結果の一部を使用して2回目の要求を行うなど)に便利です。

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

をチェックしますそれはうまくいく;) – Michael

関連する問題