Swift3、RxAlamofire和映射到自定义对象
Swift 3, RxAlamofire and mapping to custom object
我创建了一个简单的项目来检查像 RxAlamofire 和 AlamofireObjectMapper 这样的库。我有一个简单的 ApiService
和一个端点,其中 PHP
脚本可以正常工作,returns JSON
。我想调用 recipeURL
并使用 flatMap
运算符来获取响应并将其提供给 Mapper
我应该得到 Recipe
对象的地方。我该怎么做?
或者有其他方法吗?
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)
})
}
}
根据 RxAlamofire
的自述文件,库中似乎存在一种方法 json(_:_:)
。
通常,您宁愿使用 map
而不是 flatMap
将返回的数据转换为另一种格式。如果您需要订阅一个新的可观察对象(例如,使用第一个请求的部分结果进行第二个请求),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
}
我创建了一个简单的项目来检查像 RxAlamofire 和 AlamofireObjectMapper 这样的库。我有一个简单的 ApiService
和一个端点,其中 PHP
脚本可以正常工作,returns JSON
。我想调用 recipeURL
并使用 flatMap
运算符来获取响应并将其提供给 Mapper
我应该得到 Recipe
对象的地方。我该怎么做?
或者有其他方法吗?
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)
})
}
}
根据 RxAlamofire
的自述文件,库中似乎存在一种方法 json(_:_:)
。
通常,您宁愿使用 map
而不是 flatMap
将返回的数据转换为另一种格式。如果您需要订阅一个新的可观察对象(例如,使用第一个请求的部分结果进行第二个请求),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
}