I have an Windows WEB API with the following method:
public async Task<IHttpActionResult> SaveContract([FromBody] ModelDTO model)
{
string custName = model.CustomerName;
...
}
The Model I want looks like this:
public class ModelDTO
{
public int CustomerNumber { set; get; }
public string CustomerName { set; get; }
public string CustomerMail { set; get; }
public string imageDataBase64 { set; get; }
}
I want to call the API with my iOS App (Swift 4) with Alamofire 4.7.2 My dev server has a self-signed certificate. So I need to disable the evaluation.
let defaultManager: Alamofire.SessionManager = {
let serverTrustPolicies: [String: ServerTrustPolicy] = [
"devserver": .disableEvaluation
]
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders
return Alamofire.SessionManager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies))
}()
let webApi: String = "https://devserver:7208/api/KP/SaveContract"
let data = UIImageJPEGRepresentation(photoImageView.image!,1) //got the Data form an image view
var imgString: String = ""
imgString = data.base64EncodedString()
let Param = Parameters = [
"CustomerNumber": 1,
"CustomerName": "Test Name",
"CustomerMail": "test@test.com",
"imageDataBase64": imgString]
defaultManager.upload(
multipartFormData: { multipartFormData in
for (key, value) in contAsJsonParam {
multipartFormData.append("\(value)".data(using: .utf8)!, withName:key)
}
},
to: webApi,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
//lbl sichtbar machen
}
case .failure(let encodingError):
print(encodingError)
}
})
Call the api without image with Alamofire.request works, but with image request, it dosen't work. (bad ssl error) So I try the upload method, but upload dosen't work in any way (with or without image string)
If I call the Api with Alamofire.upload I got a system.net.http.unsupportedmediatypeexception
"No MediaTypeFormatter is available to read an object of type 'ModelDTO' from content with media type 'multipart/form-data'."
I try to make the upload class as json by at "headers: Content-Type:application/json" but no effect.
I try to fix it by putting
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));
in the WebApiConfig. Then i got an other error I got an NullReferenceException in the api at the line "string custName = model.CustomerName;"
You can use this code. I have tested this code with multipart data. It's working fine for me.
let url = "https://devserver:7208/api/KP/SaveContract"
//imp data need to be dynamic
let parameters: NSMutableDictionary = ["userId":"1123",
"caption":"hello how are you",
"keyword":"First Post",
"askPrice":"12345",
"postScope":"1",
"commentStatus":"1",
"gender":"male",
"email":"asd@asd.com"
]
var dictionaryHeaders = [String : String]()
dictionaryHeaders = ["Content-Type": "application/x-www-form-urlencoded" ]
Alamofire.upload(multipartFormData: { (multipartFormData) in
for (key, value) in parameters {
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as! String)
}
self.postImage = UIImage(named:"YOUR IMAGE NAME")
if let data = UIImageJPEGRepresentation(self.postImage,1) {
multipartFormData.append(data, withName: "postPic", fileName: "image.png", mimeType: "image/png")
}
}, usingThreshold: UInt64.init(), to: url, method: .post, headers: dictionaryHeaders ) { (result) in
switch result{
case .success(let upload, _, _):
upload.responseJSON{ response in
print(response)
}
case .failure(let error):
print("Error in upload: \(error.localizedDescription)")
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.