gpt4 book ai didi

Swift 3、RxAlamofire 和映射到自定义对象

转载 作者:行者123 更新时间:2023-11-28 09:53:58 25 4
gpt4 key购买 nike

我创建了一个简单的项目来检查像 RxAlamofire 和 AlamofireObjectMapper 这样的库。我有一个简单的 ApiService,其中有一个端点是 PHP 脚本,它可以正常工作并返回 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
}

关于Swift 3、RxAlamofire 和映射到自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40334098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com