我有参数
var Param : [String:String] = [:]
我正在使用
Alamofire.upload(
multipartFormData: { multipartFormData in
但作为回应它说invalid service
是他们的参数编码出错了吗?
答案 0 :(得分: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)
}
})
如果您想调用帖子请求,请尝试使用以下代码:
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)
}
}
答案 1 :(得分:0)
对于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)")
}
}
答案 2 :(得分:0)
第一个答案是针对简单的帖子API。如果要发布Multipart数据,请使用以下方法..
/**
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
})