AlamoCodable 2.0.1

AlamoCodable 2.0.1

Maintained by Umesh Verma.



  • By
  • Umesh Verma

AlamoCodable

A Network manager depend to Alamofire which automatically converts JSON response data into swift objects using Codable.

Usage

Given a URL which returns data in the following form:

{
    "total_count": 1,
    "incomplete_results": false,
    "items": [
        {
            "login": "umeshiscreative",
            "id": 36879900,
            "node_id": "MDQ6VXNlcjM2ODc5OTAw",
            "avatar_url": "https://avatars2.githubusercontent.com/u/36879900?v=4",
            "gravatar_id": "",
            "url": "https://api.github.com/users/umeshiscreative"
        }
    ]
}

You can use the class as the follows:

import AlamoCodable

let URL = "https://api.github.com/search/users?q=umeshiscreative"
        
let apiRequest = AlamoCodable(url: URL)
apiRequest.responseObject(UserModel.self){ result in
     switch result {
           case .success(let data):
                print("Sucess === \(data)")
           case .failure(let error):
                print("Error \(error)")
     }
}

If your data Response is an array format then follows:

import AlamoCodable

let URL = "https://api.github.com/search/users?q=umeshiscreative"
        
let apiRequest = AlamoCodable(url: URL)
apiRequest.responseArray(UserModel.self){ result in
     switch result {
           case .success(let data):
                print("Sucess === \(data)")
           case .failure(let error):
                print("Error \(error)")
     }
}

The UserResponse object in the completion handler is a custom object which you define. The only requirement is that the object must conform to Codable protocol. In the above example, the UserResponse object looks like the following:

struct UserModel: Codable {
    var incompleteResults: Bool? = nil
    var totalCount: Int?         = nil
    var items:[Items]?           = nil
    
    enum CodingKeys: String, CodingKey {
        case items
        case totalCount = "total_count"
        case incompleteResults = "incomplete_results"
    }
}

struct Items: Codable {
    var login:String?       = nil
    var id:Int?             = nil
    var nodeId:String?      = nil
    var avatarUrl:String?   = nil
    var gravatarId:String?  = nil
    var url:String?         = nil
    
    enum CodingKeys: String, CodingKey {
        case login
        case id
        case url
        case nodeId = "node_id"
        case avatarUrl = "avatar_url"
        case gravatarId = "gravatar_id"
    }
}
POST Request With Parameters
let parameters: Parameters = [
    "foo": "bar",
    "baz": ["a", 1],
    "qux": [
        "x": 1,
        "y": 2,
        "z": 3
    ]
]

let apiRequest = AlamoCodable(method: <HTTPMethod>, url: <String>, parameters: parameters, headers: <HTTPHeaders?>, encoding: <ParameterEncoding>)

apiRequest.responseObject(UserModel.self){ result in
     switch result {
           case .success(let data):
                print("Sucess === \(data)")
           case .failure(let error):
                print("Error \(error)")
     }
}
Save response object data in Core Data
let URL = "https://api.github.com/search/users?q=umeshiscreative"
        
let apiRequest = AlamoCodable(url: URL)
apiRequest.responseObjectWithPersistence(UserDataEntity.self, 
                                         managedContext: <##Your Managed Context of Core Data##>){ result in
     switch result {
           case .success(let data):
                print("Sucessfully Data Saved in Core Data and Your Data is === \(data)")
           case .failure(let error):
                print("Error \(error)")
     }
}

The UserDataEntity object in the completion handler is a custom object which you define. The only requirement is that the object must conform to NSManagedObject, Codable protocol. In the above example, the UserDataEntity object looks like the following:

public class UserDataEntity: NSManagedObject, Codable {
    
    @NSManaged public var incompleteResults: Bool
    @NSManaged public var totalCount: Int16
    
    enum CodingKeys: String, CodingKey {
        case totalCount = "total_count"
        case incompleteResults = "incomplete_results"
    }
    
    //MARK:- Required Codable Protocol Confirmation
    // MARK: - Decodable
    required convenience public init(from decoder: Decoder) throws {
    
        guard let codingUserInfoKeyManagedObjectContext = CodingUserInfoKey.managedObjectContext,
            let managedObjectContext = decoder.userInfo[codingUserInfoKeyManagedObjectContext] as? NSManagedObjectContext,
            let entity = NSEntityDescription.entity(forEntityName: "UserDataEntity", in: managedObjectContext) else {
                fatalError("Failed to decode UserDataEntity")
        }
        
        self.init(entity: entity, insertInto: managedObjectContext)
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.incompleteResults = try container.decodeIfPresent(Bool.self, forKey: .incompleteResults) ?? false
        self.totalCount = try container.decodeIfPresent(Int16.self, forKey: .totalCount) ?? 0
    }
    
    // MARK: - Encodable
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(incompleteResults, forKey: .incompleteResults)
        try container.encode(totalCount, forKey: .totalCount)
    }
}

Installation

AlamoCodable can be added to your project using CocoaPods by adding the following line to your Podfile:

pod 'AlamoCodable', '~> 1.1.0'

Contributing

Contributions are very welcome 👍😃.

Before submitting any pull request, please ensure you have run the included tests and they have passed. If you are including new functionality.

Credits

Alamofire, ObjectMapper, AlamofireObjectMapper