如何使用参数 swift 3.0 Alamofire 4.0 调用邮政服务?

Posted

技术标签:

【中文标题】如何使用参数 swift 3.0 Alamofire 4.0 调用邮政服务?【英文标题】:How to call post service with parameters swift 3.0 Alamofire 4.0? 【发布时间】:2016-12-01 06:10:27 【问题描述】:

我有参数在

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

我正在使用

Alamofire.upload(
        multipartFormData:  multipartFormData in

但作为回应它说invalid service 他们的参数编码是否出错了?

【问题讨论】:

您能否发送更多代码的详细信息? 您需要使用 URLEncoding(destination: .queryString) 对参数进行编码 Alamofire.upload( multipartFormData: multipartFormData in for (key, value) in Param multipartFormData.append(((value).data(using: .utf8))!, withName: key) 它说我“服务无效”,但目标 c 工作成功中的服务相同 分享更多代码。还要检查您的网址。如果里面有特殊字符,那么也需要编码。 【参考方案1】:

multipartFormData 用于在服务器上上传图片。因此,如果您想上传图像数据,请尝试使用以下代码。

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)

    
)

如果您想调用 post 请求,请尝试使用以下代码:

 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)
                

【讨论】:

【参考方案2】:

对于 swift 3,使用以下代码。它在我所有的项目中都非常有效..

//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)")
            
        

【讨论】:

【参考方案3】:

第一个答案是简单的 post API。如果要发布多部分数据,请使用以下方法..

 /**
     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)
            
        )
    

像这样从你的类中调用上述方法。

 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

    )

【讨论】:

以上是关于如何使用参数 swift 3.0 Alamofire 4.0 调用邮政服务?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 swift 3.0 中将此类参数发送到服务器调用

Alamofire Swift 3.0 调用中的额外参数

Swift 3.0 迁移后的 Alamofire 错误:“调用中的额外参数”(请求方法)

Swift 3.0:参数标签 '(_:) 不匹配任何可用的重载

Swift 3.0 错误:转义闭包只能按值显式捕获 inout 参数

如何使用 Swift 2.3 和 3.0 编译模块?