Migrating generic function from Alamofire 3 to Alamofire 4

MrMins

I'm migrating this code with Alamofire 3 to Alamofire 4. The reference is: Creating a generic method with AlamoFire in Swift

I have this class:

import Foundation
import Alamofire
import AlamofireObjectMapper
import ObjectMapper

class HttpHandler {

    static func sendRequest<T:BaseUser>(url: String, parameters: [String: AnyObject]?) -> T {
        let res : T
        Alamofire.request(url)
            .validate()
            .responseObject { (response: DataResponse<[T]>) in
                switch response.result {
                case .Success(let value):
                    res.valueHandle?(value)
                case .Failure(let error):
                    res.errorHandle?(error)
                }
        }

        return res
    }
}


class BaseUser: ResponseObjectSerializable {
    var valueHandle : ((BaseUser)->())?
    var errorHandle : ((NSError)->())?

    required init?(response: HTTPURLResponse, representation: AnyObject) {

    }
}

public protocol ResponseObjectSerializable {
    init?(response: HTTPURLResponse, representation: AnyObject)
}

But, I'm getting this error:

Cannot convert value of type '(DataResponse<[T]>) -> ()' to expected argument type '(DataResponse<_>) -> Void'

How I can fix it?

Sandeep

You are returning from asynchronous method, and expecting that the result is valid, I think you should rethink your implementation of sendRequest method a bit. You can make it such that it takes in completion closure.

Also, your BaseUser does not seem to be a model class, it rather seems like some handler class, so to say. It only has two properties which are closure, what are you trying to map from http request. Should it have some real attributes.

With that, if you have a pure model class and a proper send method, you can achieve what you are trying pretty easily.

The error in your case is because you are using, AlamofireObjectMapper and trying to map values without actually implementing protocol.

Look at the signature of the method,

public func responseObject<T>(queue: DispatchQueue? = default, 
                              keyPath: String? = default, 
                              mapToObject object: T? = default,
                              context: MapContext? = default,
                              completionHandler: @escaping(Alamofire.DataResponse<T>) -> Swift.Void) -> Self where T : BaseMappable

Here the generic parameter T is expected to be of type BaseMapper. If you conform to the protocol Mappable from ObjectMapper, it should be just fine.

class BaseUser: BaseMappable {

    func mapping(map: Map) {
        // map your actual properties here
        // like username, name
    }
}

I have also changed your sendRequest method a bit, such that instead of returning values, it does the request and does a callback after finishing.

static func sendRequest<T:BaseUser>(url: String,
                                    parameters: [String: AnyObject]?,
                                    completion: @escaping ([T], Error?) -> Void) {
    Alamofire.request(url)
        .validate()
        .responseObject { (response: DataResponse<[T]>) in

            switch response.result {
            case .success(let value):
                completion(value, nil)
            case .failure(let error):
                completion([], error)
            }
    }

}

The code looks fine, but it does not yet work. You are expecting that your response to be mapped to array of BaseUser, but AlamofireObjectMapper, expect it to be of type, Mappable.

Now you can use extension to array and conform to the protocol. We can make use of Swift 4.1 Conditional Conformance here.

extension Array: BaseMappable where Element: BaseMappable {

    public mutating func mapping(map: Map) {
        var userHolder: [BaseUser] = []
        // map array of values to your BaseUser
    }
}

And with this you are good to go. Note, that I showed you how the problem that you had could be solved. I also did some small refactoring just to make code more clearer.

Please make changes according to your need.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Generic function with Alamofire

From Dev

What is the best solution to fix defects after migrating to Alamofire 4 and Swift3

From Dev

Using a value from Alamofire request outside the function

From Dev

Returning a value from a function with Alamofire and SwiftyJson

From Dev

Cannot call value of non-function type 'HTTPURLResponse?' Alamofire 4, Swift 3

From Dev

Creating a generic method with AlamoFire in Swift

From Dev

Alamofire 4 swift 3 Uploading MultipartFormData with header not posting

From Dev

Alamofire 4 and Swift 3 Image upload with other parameters

From Dev

Upload a photo to Django in Swift 3 using Alamofire 4?

From Dev

Swift 3: How to add or remove parameters in Request Body in ALamofire 4?

From Dev

How to return respond result to function with Alamofire Swift 3

From Dev

Nothing showing in app from JSON url with Swift 3 and Alamofire

From Dev

Migration Alamofire swift2 from swift 3

From Dev

Alamofire "Generic Response Object Serialization" does not compile

From Dev

Creating generic fetcher using Alamofire JSOn and HTML

From Dev

Alamofire "Generic Response Object Serialization" does not compile

From Dev

Alamofire json request Swift 3

From Dev

Uploading a file with Swift 3 and Alamofire

From Dev

Alamofire timeout not working in Swift 3

From Dev

How to return value from Alamofire

From Dev

Alamofire get response from POST

From Dev

Cannot call value of non-function type '((UInt) -> Data?)!' with Alamofire 4

From Dev

How to fill images in to UICollectionView with Alamofire Swift 4

From Dev

How to upload image as a parameter, with other parameters using multipart form data in ios, swift3, Alamofire 4

From Dev

Compiler error in custom Alamofire response function

From Dev

Call a function before/after each Alamofire request

From Dev

Error - Resquest function with Alamofire and AlamofireObjectMapper (swift - iOS)

From Dev

JSON parse error from server when making request with Alamofire in swift 4

From Dev

get value of nested array alamofire swift 3

Related Related

  1. 1

    Generic function with Alamofire

  2. 2

    What is the best solution to fix defects after migrating to Alamofire 4 and Swift3

  3. 3

    Using a value from Alamofire request outside the function

  4. 4

    Returning a value from a function with Alamofire and SwiftyJson

  5. 5

    Cannot call value of non-function type 'HTTPURLResponse?' Alamofire 4, Swift 3

  6. 6

    Creating a generic method with AlamoFire in Swift

  7. 7

    Alamofire 4 swift 3 Uploading MultipartFormData with header not posting

  8. 8

    Alamofire 4 and Swift 3 Image upload with other parameters

  9. 9

    Upload a photo to Django in Swift 3 using Alamofire 4?

  10. 10

    Swift 3: How to add or remove parameters in Request Body in ALamofire 4?

  11. 11

    How to return respond result to function with Alamofire Swift 3

  12. 12

    Nothing showing in app from JSON url with Swift 3 and Alamofire

  13. 13

    Migration Alamofire swift2 from swift 3

  14. 14

    Alamofire "Generic Response Object Serialization" does not compile

  15. 15

    Creating generic fetcher using Alamofire JSOn and HTML

  16. 16

    Alamofire "Generic Response Object Serialization" does not compile

  17. 17

    Alamofire json request Swift 3

  18. 18

    Uploading a file with Swift 3 and Alamofire

  19. 19

    Alamofire timeout not working in Swift 3

  20. 20

    How to return value from Alamofire

  21. 21

    Alamofire get response from POST

  22. 22

    Cannot call value of non-function type '((UInt) -> Data?)!' with Alamofire 4

  23. 23

    How to fill images in to UICollectionView with Alamofire Swift 4

  24. 24

    How to upload image as a parameter, with other parameters using multipart form data in ios, swift3, Alamofire 4

  25. 25

    Compiler error in custom Alamofire response function

  26. 26

    Call a function before/after each Alamofire request

  27. 27

    Error - Resquest function with Alamofire and AlamofireObjectMapper (swift - iOS)

  28. 28

    JSON parse error from server when making request with Alamofire in swift 4

  29. 29

    get value of nested array alamofire swift 3

HotTag

Archive