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

后端 未结 3 1187
忘了有多久
忘了有多久 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:23

    multipartFormData is used to upload images on server. So if you want to upload image data then try to use below code.

    let payload: [String: AnyObject] = [
    "key1": "val1" as AnyObject,
    "key2": true as AnyObject,
    "key3" : [1,2,3,4] as AnyObject
    ]
    
    let requestString = "http://www.url.com/api/action"
    
    Alamofire.upload(multipartFormData: { (multipartFormData) in
        multipartFormData.append(UIImageJPEGRepresentation(self.photoImageView.image!, 0.5)!, withName: "photo_path", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
        for (key, value) in payload {
            multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
        }
        }, to: requestString, method: .post , headers:nil, encodingCompletion: { (result) in
        switch result {
        case .success(let upload, _, _):
    
            upload.uploadProgress(closure: { (progress) in
                print(progress.fractionCompleted * 100)
            })
    
            upload.responseJSON(completionHandler: { (response) in
            })
        case .failure(let error):
            print(error)
    
        }
    })
    

    If you want to call the post request then try to use below code:

     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)
                    }
    }
    
    0 讨论(0)
  • 2020-12-12 07:30

    The first Answer is for simple post API. If you want to post Multipart data then use the following Method..

     /**
         Call this to create a request with any HTTP method
    
         - parameter httpMethodType: HTTP method type post,get etc
         - parameter headers:        HTTP header key-value pair (no need to Content-Type,Accept)
         - parameter serviceName:    name of service which need to call
         - parameter paramDic:       parameters in key-value pair
         - parameter files:          array of NSData objects for file content
         - parameter success:        success callback handler
         - parameter failure:        failure callback handler
         */
        func uploadFileRequestWithParameters(_ paramDic : NSMutableDictionary?, files: NSMutableArray?, headers : NSMutableDictionary?, serviceName : NSString, success: @escaping (( _ response : HTTPURLResponse?, _ data : NSDictionary?) -> Void), failure: @escaping ((_ error : Error? ) -> Void)) {
    
            let urlString = BASE_URL + (serviceName as String)
            let url : URL = URL.init(string: urlString)!
            var headerDic = [String : String]()
            headerDic["Content-Type"] = "multipart/form-data"
    
            if headers != nil {
                let allHeaders : NSArray = headers!.allKeys as NSArray
                for key in allHeaders {
                    headerDic[(key as? String)!] = (headers!.object(forKey: key)! as? String)
                }
            }
            print("Full HTTP URL -> \(urlString)")
            print("HTTP Request Method -> POST")
            print("Full HTTP Headers -> \(headerDic)")
            print("Full HTTP Parameters -> \(paramDic)")
            print("Files Array -> \(files)")
    
            // Begin upload
    
            alamoFireManager?.upload(multipartFormData: { (multipartFormData) in
    
                // import image to request
                for (file)  in files! {
                    var mimeTypeStr = ""
                    let fileDic : NSDictionary = file as! NSDictionary
                    if (fileDic.object(forKey: "fileType") as? String == "image" ) {
                        mimeTypeStr = "image/png";
                    }
                    else if (fileDic.object(forKey: "fileType") as? String == "video" ) {
                        mimeTypeStr = "video/mp4";
                    }
                    else if (fileDic.object(forKey: "fileType") as? String == "gif" ) {
                        mimeTypeStr = "image/gif";
                    }
                    multipartFormData.append(fileDic.object(forKey: "fileData") as! Data, withName: fileDic.object(forKey: "fileKey") as! String, fileName: fileDic.object(forKey: "fileName") as! String, mimeType: mimeTypeStr)
                }
    
                // import parameters
                for (key, value) in paramDic! {
                    multipartFormData.append((value as! String).data(using: String.Encoding.utf8)!, withName: key as! String)
                }
            },
            usingThreshold: SessionManager.multipartFormDataEncodingMemoryThreshold, to: url, method: .post, headers: headerDic as [String : String], encodingCompletion: {
                        encodingResult in
    
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON(completionHandler: { response in
                        debugPrint(response)
                        print(response.result.value as? NSDictionary)
                    })
    
                case .failure(let error):
                    print(error)
                }
            })
        }
    

    Call above method from your class like this.

     let image : UIImage = #imageLiteral(resourceName: "splash")
            let imgData : Data = UIImagePNGRepresentation(image)!
            // let fileArray : NSArray = NSArray.init(objects: imgData)
    
            let parameters : NSMutableDictionary = [
                "name" : "Krishna",
            ]
            //Array to store file data
            let filesArray : NSMutableArray = []
            //fileType = image/video/gif
            //fileKey = api parameter key to receive file
            //Dictionary to hold the individual file data
            let file1 : NSMutableDictionary = [
                "fileData" : imgData,
                "fileName" : "profileImage.png",
                "fileType" : "image",
                "fileKey" : "userProfileImg"
            ]
            let file2 : NSMutableDictionary = [
                "fileData" : imgData,
                "fileName" : "video.mp4",
                "fileType" : "video",
                "fileKey" : "myVideoKey"
            ]
            let file3 : NSMutableDictionary = [
                "fileData" : imgData,
                "fileName" : "image.gif",
                "fileType" : "gif",
                "fileKey" : "myGIFKey"
            ]
            //Adding all file data dictionaries to array
            filesArray.add(file1)
            filesArray.add(file2)
            filesArray.add(file3)
    
            let header : NSMutableDictionary  = [
            "version": "1.0",
            "os": "iOS",
            "token" : HEADER_TOKEN
        ]
    
           uploadFileRequestWithParameters(paraDic, files: files , headers: header, serviceName: UPDATE_PROFILE_API as NSString, success: { (response, data) in
             } , failure: { (error) in
    
        })
    
    0 讨论(0)
  • 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)")
                }
            }
    
    0 讨论(0)
提交回复
热议问题