Cagatay
Cagatay

Reputation: 392

POST request with data in body with Alamofire 4

how is it possible to send a POST request with a data in the HTTP body with Alamofire 4? I used custom encoding at swift 2.3 it was working good. I converted my code swift 3 and I tried to paramater encoding but not working. This code :

public struct MyCustomEncoding : ParameterEncoding {
private let data: Data
init(data: Data) {
    self.data = data
}
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {

    var urlRequest = try urlRequest.asURLRequest()        
    do {            
            urlRequest.httpBody = data
            urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")

    } catch {
        throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
    }

    return urlRequest
}

and Alamofire request :

let enco : ParameterEncoding = MyCustomEncoding(data: ajsonData)
    Alamofire.request(urlString, method: .post , parameters: [:], encoding: enco , headers: headers).validate()
                .responseJSON { response in
                    switch response.result {
                    case .success:
                        print(response)

                        break
                    case .failure(let error):

                        print(error)
                    }
    }

Upvotes: 28

Views: 69302

Answers (4)

Srinivasan_iOS
Srinivasan_iOS

Reputation: 1078

Alamofire using post method

class ViewController: UIViewController {
    let parameters = [
        "username": "foo",
        "password": "123456"
    ]
    let url = "https://httpbin.org/post"

override func viewDidLoad() {
        super.viewDidLoad()
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: [:]).responseJSON {
            response in
            switch (response.result) {
            case .success:
                print(response)
                break
            case .failure:
                print(Error.self)
            }
        }
}

Upvotes: 5

Super Developer
Super Developer

Reputation: 897

Please find the code below

**

pod 'Alamofire', '~> 5.4'

** **

pod 'ObjectMapper', '~> 4.2'

** **

pod 'SwiftyJSON'

**

pod 'TPKeyboardAvoiding'

Use Model

import ObjectMapper
        
class LoginModel : Mappable{
        
        var status : String?
        var data : [DataModel]?
        var message : String?
    
        required init?(map: Map) {
        }
    
        func mapping(map: Map) {
            status <- map["status"]
            data <- map["data"]
            message <- map["message"]
        }
    }
    
    class DataModel : Mappable{
        var access_token : String?
        var isvideo : String?
        
        required init?(map: Map) {
            
        }
        
        func mapping(map: Map) {
            access_token <- map["access_token"]
            isvideo <- map["isvideo"]
        }
    }

Call API

HTTPNetwork().getHTTPData("", parameters: LoginParameter, completion: {(successresponse) -> Void in
                
                if let res = successresponse{
                    print("sucess token \(res["message"].string!)")
                    if let myuser = Mapper<DataModel>().map(JSONString: res["data"].rawString()!){
                        print("access_token \(myuser.access_token)")
                    }
                }
            }, error: {(errorresponse)-> Void in
                if let res = errorresponse{
                    print("Error response token \(res)")
                }
            })


public func getHTTPData(_ request: String, parameters : Parameters?, completion: @escaping (  JSON?) -> Void, error: @escaping ( JSON?) -> Void){
    AF.request(URL.init(string: "url")!, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: ["Content-Type":"application/json"]).responseJSON { (response) in
        print(response.result)
        
        switch response.result{
        case .success:
            if let json = response.value as? [String : Any]{
                if let output:JSON = JSON(response.value!){
                    if json["isSuccess"] as? Int == 1{
                        completion(output)
                    }else{
                        error(output)
                    }
                }
            }else{
                completion(nil)
            }
        case .failure:
            completion(nil)
        }
    }
}

Upvotes: -1

Ekta Padaliya
Ekta Padaliya

Reputation: 5799

You need to send request like below in swift 3

let urlString = "https://httpbin.org/get"

Alamofire.request(urlString, method: .post, parameters: ["foo": "bar"],encoding: JSONEncoding.default, headers: nil).responseJSON {  
response in
  switch response.result {
                case .success:
                    print(response)

                    break
                case .failure(let error):

                    print(error)
                }
}

Swift 5 with Alamofire 5:

AF.request(URL.init(string: url)!, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
        print(response.result)

        switch response.result {

        case .success(_):
            if let json = response.value
            {
                successHandler((json as! [String:AnyObject]))
            }
            break
        case .failure(let error):
            failureHandler([error as Error])
            break
        }
    }

Upvotes: 66

Raghib Arshi
Raghib Arshi

Reputation: 755

This will work better in Swift 4.

let url = "yourlink.php". // This will be your link
let parameters: Parameters = ["User_type": type, "User_name": name, "User_email": email, "User_contact": contact, "User_password": password, "from_referral": referral]      //This will be your parameter

Alamofire.request(url, method: .post, parameters: parameters).responseJSON { response in
    print(response)
}

Upvotes: 4

Related Questions