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

标签 swift swift3 alamofire rx-swift

我创建了一个简单的项目来检查像 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/

相关文章:

swift - 我应该在 swift 中使用 For - in 循环来设置字段值吗

swift - 在 VIPER 架构中在哪里以及如何执行转场?

ios - 快速自动更改背景图像

ios - 如何在 SWIFT 中获取 MP3 比特率

swift - 结构/类定义中的私有(private)部分 swift 3

swift - Alamofire 多参数字典

ios - 向 UITextField、UILabel、UIView 自定义类添加自定义功能

alamofire - 我的图像是否使用 Alamofire 和 AlamofireImage 自动缓存

ios - 访问 AlamoFire 框架中的映射对象返回 nil 值

ios - AlamofireObjectmapper 对模型属性进行编码