Latest 2.0.1
Homepage https://github.com/umeshiscreative/AlamoCodable
License MIT
Platforms ios 10.0, requires ARC
Dependencies Alamofire
Authors

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 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
    @NSManaged public var items: Set<Items>?

    enum CodingKeys: String, CodingKey {
        case items
        case totalCount         = "total_count"
        case incompleteResults  = "incomplete_results"    
    }

    //MARK:- Required Codable Protocol Confirmation
    required convenience public init(from decoder: Decoder) throws {

        //Access ManagedObject from AlamoCodable init: with Params
        let object = AFManagedObject(decoder, enitityName: String(describing: UserDataEntity.self))

        self.init(entity: object.getManageedObject().entity, insertInto: object.getManageedObject().managedObjectContext)

        //Access Container with Codeing Keys
        let container = try decoder.container(keyedBy: CodingKeys.self)

        //Decode the varibles from container
        self.incompleteResults = try container.decodeIfPresent(Bool.self, forKey: .incompleteResults) ?? false
        self.totalCount = try container.decodeIfPresent(Int16.self, forKey: .totalCount) ?? 0

        //Decode Relation object with its key values
        let itemsArray = try container.decode([Items].self, forKey: .items)
        self.items = Set(itemsArray)

    }

    // 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', '~> 2.0.1'

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

Latest podspec

{
    "name": "AlamoCodable",
    "platforms": {
        "ios": "10.0"
    },
    "version": "2.0.1",
    "license": "MIT",
    "summary": "AlamoCodable is a network manager depend on Alamofire.",
    "homepage": "https://github.com/umeshiscreative/AlamoCodable",
    "authors": {
        "Umesh Verma": "[email protected]"
    },
    "source": {
        "git": "https://github.com/umeshiscreative/AlamoCodable.git",
        "tag": "2.0.1"
    },
    "swift_version": "4.0",
    "requires_arc": true,
    "source_files": "AlamoCodable/**/*.swift",
    "dependencies": {
        "Alamofire": [
            "~> 4.7"
        ]
    }
}

Pin It on Pinterest

Share This