How to call post service with parameters swift 3.0 Alamofire 4.0?

后端 未结 3 1210
忘了有多久
忘了有多久 2020-12-12 06:42

I have parameters in

var Param : [String:String] = [:]

I am using

Alamofire.upload(
        multipartFormData: { multipar         


        
3条回答
  •  死守一世寂寞
    2020-12-12 07:46

    For swift 3, use the following code. It works very well in all my projects..

    //Parameters
    
    let paramDic : NSMutableDictionary = [
                "key1" : "value1",
                "key2" : "value2",
            ]
    
    let urlString = "www.mywebsite.net/api/"
    let url : URL = URL.init(string: urlString)!
    var request = URLRequest(url: url)
    
    //Setting HTTP method GET/POST/PUT
    request.httpMethod = "POST"
    
    //Setting header
    
    request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
    request.setValue("application/json", forHTTPHeaderField: "Accept")
    
    //Setting parameters
    
    request.httpBody = try! JSONSerialization.data(withJSONObject: paramDic!, options: [])
    
    
    
    if paramDic != nil {
                request.httpBody = try! JSONSerialization.data(withJSONObject: paramDic!, options: [])
            }
    
    alamoFireManager!.request(request as URLRequestConvertible).responseJSON {
                response in
                switch response.result {
                case .failure(let error):
                    print("\(urlString) failure response -> \n NSHTTPURLResponse ->\(response.response) \n \(error)")
                case .success :
                    print("\(urlString) success response -> \n NSHTTPURLResponse ->\(response.response) \n Data -> \(response.result.value as? NSDictionary)")
                }
            }
    

提交回复
热议问题