Generic function with Alamofire

alamofire 5
alamofire 5 codable
alamofire codable
alamofire documentation
alamofire post request swift 5
alamofire download file
alamofire upload

I work with iOS app that use Alamofire, I want to write a generic function(s) which used to send and retrieve data from server to a decodable objects, my function was as below :

func pop <T : Codable>  (_ Url: inout String, _ popedList: inout [T]) {
    let url = URL(string:Url)
    Alamofire.request(url!, method: .post).responseJSON { response in
        let result = response.data
        do {
            let data = try JSONDecoder().decode(popedList, from: result!)// get error here
            print(data[0])

            let jsonEncoder = JSONEncoder()
            let jsonData = try! jsonEncoder.encode(data[0])
            let jsonString = String(data: jsonData, encoding: .utf8)
            print("jsonString: \(String(describing: jsonString))")

        } catch let e as NSError {
            print("error : \(e)")
        }
    }
} 

and a function to send an object to server as below:

func push <T : Codable>  (_ Url: inout String, _ pushObject: inout T) {
    let jsonData = try! JSONEncoder().encode(pushObject)
    let jsonString = String(data: jsonData, encoding: .utf8)
    print("jsonString: \(String(describing: jsonString))")

    let url = URL(string:Url)

    Alamofire.request(url!,
                      method: .post,
                      parameters:jsonString)//it's need to creat a Dictionary instate of String
        .validate(statusCode: 200..<300)
        .validate(contentType: ["application/json"])
        .response { response in
            // response handling code
             let result = response.data
            print(response.data)
    }
}

I get an error in first function,

"Cannot invoke 'decode' with an argument list of type '([T], from: Data)'"

and

"Escaping closures can only capture inout parameters explicitly by value"

What is the best way to write these to function as generic?

After a few searches and trying to edit my functions I capable to rewrite my two functions in such away that I get what I need:

 func pop<T: Decodable>(from: URL, decodable: T.Type, completion:@escaping (_ details: [T]) -> Void)
            {
       Alamofire.request(from, method: .post).responseJSON { response in
                let result_ = response.data
                do {
                    let data = try JSONDecoder().decode([T].self, from: result_!)
                    //let data = try JSONDecoder().decode(decodable, from: result_!)// get error here
                    //print(data[0])
                    print("data[0] : \(data[0])")
                    completion(data)
                } catch let e as NSError {
                    print("error : \(e)")
                }
            }
        }

    func push <T : Codable>  (_ Url:  String, _ pushObject:  T)
        {
            let jsonData = try! JSONEncoder().encode(pushObject)
            let jsonString = String(data: jsonData, encoding: .utf8)
            print("jsonString: \(String(describing: jsonString))")

            let url = URL(string:Url)

            Alamofire.request(url!,
                              method: .post,
                              parameters:convertToDictionary(text: jsonString!))//it's need to creat a Dictionary instate of String
                .validate(statusCode: 200..<300)
                .validate(contentType: ["application/json"])
                .response { response in
                    // response handling code
                    print(response.data!)
                    if let jsonData = response.data {
                        let jsonString = String(data: jsonData, encoding: .utf8)
                        print("response.data: \(String(describing: jsonString))")
                    }
            }
        }

        func convertToDictionary(text: String) -> [String: Any]? {
            if let data = text.data(using: .utf8) {
                do {
                    return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
                } catch {
                    print(error.localizedDescription)
                }
            }
            return nil
        }

Creating a generic method with AlamoFire in Swift, you can use a BaseObject to do this easy : class BaseUser: ResponseObjectSerializable { var valueHandle : ((BaseUser)->())? var errorHandle : ((NSError)->())? Generic wrapper for Alamofire Request's function jsonResponse wrapper. I am trying to wrap a responseJSON function of a Request class of Alamofire because when I send an API request I get a response in a specific pattern. I have achieved this, but I am still not satisfied with it. I can see much code repeated in both "handle" functions.

JSONDecoder().decode method takes type and data parameter. Pass type not popedList.

let data = try JSONDecoder().decode([T].self, from: result!)

Inout Paramaters Function parameters are constants by default. Trying to change the value of a function parameter from within the body of that function results in a compile-time error. This means that you can’t change the value of a parameter by mistake. If you want a function to modify a parameter’s value, and you want those changes to persist after the function call has ended, define that parameter as an in-out parameter instead.

You are not changing value of popedList in both functions, so using inout is meaningless.

Alamofire and Swift, Alamofire (https://github.com/Alamofire/Alamofire) is an incredible Swift a lot of helper functions and one thing that really appealed to me, generic response  Protocol Oriented Generic Network Layer example with Alamofire and Swift4 networking protocol-oriented network alamofire generic-functions generics generic-programming swift4 Updated Sep 30, 2019

Alamofire Generic Response Object Serialization using 'Codable', Using Swift extension we add functions to decode incoming JSON into our model struct/class that we will update afterward. let decoder = JSONDecoder() let  The build target for Alamofire will be listed as either Alamofire iOS, Alamofire macOS, Alamofire tvOS or Alamofire watchOS. And that's it! The Alamofire.framework is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device.

alexiscn/GenericNetworking: Generic Networking , Generic Networking Framework base on Alamofire and Codable requestJSON(​baseURLString: "https://api.github.com", path: "/gists", method: .get,  Alamofire should support both generic Decodable response parsing and specific JSONDecoder and PropertyListDecoder based response handlers.

Generic type 'DataResponse' specialized with too few type , Versions i use: AlamofireObjectMapper 6.1.0 ObjectMapper 3.5.1 Alamofire 5.0.0​-rc.2 Problem with .responseArray: AF.request(getUrlAPI(. EVReflection is used in EVCloudKitDao and EVWordPressAPI. In most cases EVReflection is very easy to use. Just take a look the section It's easy to use. But if you do want to do non standard specific things, then EVReflection will offer you an extensive range of functionality. Available extensions

Generic wrapper for Alamofire Request's function jsonResponse , I am trying to wrap a responseJSON function of a Request class of Alamofire because when I send an API request I get a response in a specific  It seems to me as if Alamofire (which is already a dependency) defines its own Result type throwing problems when trying to write functions that return results. For example Xcode (7.0 beta 5) tells me that I can't write Result<MyDataType, MyErrorType> because Generic type 'Result' specialized with too many type parameters (got 2, but expected 1) .

Comments
  • There are a lot of bad practices in both functions. You shouldn't use inout parameters in Swift unless you absolutely need to. Also don't use forced casting, forced unwrapping and forced try, handle errors gracefully.
  • Can you rewrite entire function and How to call it?
  • Can you rewrite entire function and How to call it?