json - Swift 将 ObjectMapper 与单例一起使用

标签 json swift objectmapper

我想在单例情况下使用 ObjectMapper 解析 Json 字符串。示例代码:

class User: Mappable {

    var username: String?
    var signature: String?

    //Singleton
    static let shared = User()
    private init() {}

    //Mappable functions
    required init?(map: Map) {}

    func mapping(map: Map) {
        username <- map["username"]
        signature <- map["signature"]
    }

    //Update userInfo after network request
    func getUserInfo() {
        //Network things
        ...
        //Example data
        let data = [
            "username": "Eason",
            "signature": "I love U"
        ]

        //Some thing like this to update userInfo
        Mapper<User>().map(data)
    } 

}

那么,在单例情况下,ObjectMapper 的正确使用方法是什么?

最佳答案

我更喜欢以下选项。

1) 用户管理器(单例):

class UserManager: NSObject {

    static let shared = UserManager()

    var profile: UserProfile?

    private override init() {}

    func loadUserProfile(completion: @escaping () -> ()) {

        RestClient.shared.getUserProfile() { [weak self] (profile, error) in

            guard let `self` = self else { return }

            self.profile = profile as? UserProfile

            completion()
        }
    }
}

2) 用户模型:

class UserProfile: Mappable {

    var username: String?
    var signature: String?

    required init?() {}
    required init?(map: Map) {}

    func mapping(map: Map) {
        username   <- map ["username"]
        signature  <- map ["signature"]
    }

}

3) 休息客户端

typealias IdResponseBlock = (_ swiftObj: Any?, _ error: Error?) -> Void

class RestClient: NSObject {

    static let shared = RestClient()

    // Additional class where sending and receiving information from the server occurs
    private var http = HttpService()

    let baseUrl = ApiSettings.shared.kServerBaseURL

    override init() {
        super.init()
    }

    func parseData<P: BaseMappable>(object: Any, modelCls: P.Type, response: (IdResponseBlock)) {

        if object is NSArray {
            let result = Mapper<P>().mapArray(JSONObject: object)
            return response(result, nil)
        }

        if object is NSDictionary {
            let model: P = Mapper<P>().map(JSONObject: object)!
            return response(model, nil)
        }
    }

    //MARK: - API

    //MARK: - User

    func getUserProfile(resp: @escaping IdResponseBlock) {

        let url = baseUrl + Requests.profile

        http.queryBy(url, method: .get, queue: .background, resp: { (response, error) in

            if let err = error {
                return resp(nil, err)
            }

            guard let data = response else {
                return resp(nil, error)
            }

            let jsonData = JSON(data)["data"]

            self.parseData(object: jsonData.rawValue,
                           modelCls: UserProfile.self,
                           response: resp)
        })
    }
}

关于json - Swift 将 ObjectMapper 与单例一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43930599/

相关文章:

swift - 使用 userdefault 保存并获取模型类的详细信息

c# - 统一: Saving/Loading Sprites as Json

iphone - AFNetworking 预期内容类型错误

swift - Alamofire SSL 失败

ios - 在 Swift 中可靠地获取 iOS 应用程序的 “~/Library” 路径

ios - NS_Deprecated 等效于 3rd 方框架

java - 如何忽略 jackson 注释?

android - 如何在 Java 中创建嵌套的 Json 对象?

java - com.fasterxml.jackson.databind.exc.MismatchedInputException : Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token

scala - scala/java 中的 Camel 案例 json 到蛇案例 json