swiftxcodealamofireobjectmapperalamofire5

How to map Alamofire 5.2 response with ObjectMapper in Swift5


I have a model like this:

import UIKit
import ObjectMapper

struct Token: Mappable {

    var token: String?
    var deviceId: String?

    init?(map: Map) {

    }


   mutating func mapping(map: Map) {
        token <- map["token"]
        deviceId <- map["device_id"]
    }

}             

So send a request with Alamofire like this:

import ObjectMapper
import Alamofire
  override func viewDidLoad() {
    super.viewDidLoad()
    let request = ...
    AF.request(request).validate(statusCode: 200..<300).responseJSON { (response:AFDataResponse<Any>) in

               let token = Mapper<Token>().map(JSONString: serviceResponse.value) ‌//Not work   


   }
}  

When print my response that is correct but, I can't map it to my object model with ObjectMapper.


Solution

  • If you need return Value:

        func getUserMapple(completionHandler: @escaping (_ userData: UserMappable) -> ()) {
            
            guard let urlString = URL(string: userUrl) else { return }
            
            AF.request(urlString).responseJSON { (responce) in
                
                switch responce.result {
                case .success(let value):
                    guard let castingValue = value as? [String: Any] else { return }
                    guard let userData = Mapper<UserMappable>().map(JSON: castingValue) else { return }
                completionHandler(userData)
                case .failure(let error):
                    print(error.localizedDescription)
                }
            }
      }
    

    If you need return Array:

        func getUserMapple(completionHandler: @escaping (_ dotaData: [DotaModelMapable]) -> ()) {
            
            guard let urlString = URL(string: dotaUrl) else { return }
            
            AF.request(urlString).responseJSON { response in
                
                switch response.result {
                case .success(let value):
                    guard let dotaData = Mapper<DotaModelMapable>().mapArray(JSONObject: value) else { return }
                    completionHandler(dotaData)
                case .failure(let error):
                    print(error.localizedDescription)
                }
            }
      }