i want to upload photo into server with almofire i'm using this code right now but i'm getting timeout
let imageData = UIImageJPEGRepresentation(croppedImage, 1)
let urlRequest = self.urlRequestWithComponents(url, imageData: imageData!)
self.alamofire.upload(urlRequest.1, to: urlRequest.0 as! URLConvertible).responseJSON { response in
guard response.result.isSuccess else {
self.showError()
return
}
guard let data = response.result.value else {
self.showError()
return
}
let json = JSON(data)
}
func urlRequestWithComponents(_ urlString:String, imageData:Data) -> (URLRequestConvertible, Data) {
var urlRequest = URLRequest(url: URL(string: urlString)!)
urlRequest.httpMethod = HTTPMethod.post.rawValue
let boundary = generateBoundaryString()
let contentType = "multipart/form-data;boundary=" + boundary
urlRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")
let uploadData = NSMutableData()
uploadData.append("\r\n--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
uploadData.append("Content-Disposition: form-data; name=\"file\"; filename=\"file.png\"\r\n".data(using: String.Encoding.utf8)!)
uploadData.append("Content-Type: image/png\r\n\r\n".data(using: String.Encoding.utf8)!)
uploadData.append(imageData)
uploadData.append("\r\n--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)
return try! (Alamofire.URLEncoding.default.encode(urlRequest, with: nil), uploadData as Data)
}
Is there any solution about this issue ?
Try this in swift 3
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imageData, withName: "photo_path", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
}, to:"http://server1/upload_img.php")
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (Progress) in
print("Upload Progress: \(Progress.fractionCompleted)")
})
upload.responseJSON { response in
//self.delegate?.showSuccessAlert()
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
// self.showSuccesAlert()
//self.removeImage("frame", fileExtension: "txt")
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
case .failure(let encodingError):
//self.delegate?.showFailAlert()
print(encodingError)
}
}
Related
I upload image with some other parameters I write this code but can't success in this code I got some error how to resolve this issue
also change parameters type(NSDictionary & String type) and Alamofire update pod.
I face this line Error
multipartFormData.append(value.data(using: String.Encoding.utf8)!,
withName: key)
error is
Value of type 'Any' has no member 'data'
Code is Hear
let parameter : NSDictionary = ["auth_key": UserDefaults.standard.value(forKey: GlobalConstants.kAuthKey)!,
"userid" : UserDefaults.standard.value(forKey: GlobalConstants.kuserId)!,
"eventname" : self.txtEventName.text!,
"eventdescription" : self.textviewDescription.text!,
"event_categories" : self.arrSelectEventID,
"eventshop" : self.selectedOrganizerID,
"eventreef" : self.selectedReefID,
"event_start_date_time" : self.Startdate,
"event_start_time" : self.startTime,
"event_end_date_time" : self.Enddate,
"event_end_time" : self.EnfTime,
"meeting_location" : self.MeetingPoint,
"meeting_location_address" : meetingAddress,
"meeting_location_latitude" : meetinglat,
"meeting_location_longitude" : meetingLong,
"event_ticket_price" : self.txtEventTicketPrice.text! ,
"event_ticket_qty" : self.txtEventTicketQuantity.text!,
"eventvideourl" : self.txtVideoURL.text!,
"recurrence_type" : "none" ,
"end" : self.End,
"end_type" : self.EndType,
"end-count" : self.EndCount,
"create_ticket_on_event" : ""]
let image = self.imgCover.image
let imageData = image?.jpegData(compressionQuality: 1)
Alamofire.upload(multipartFormData: { multipartFormData in
// import image to request
multipartFormData.append(imageData!, withName: "eventimage", fileName: "profile.jpg", mimeType: "image/jpeg")
for (key, value) in parameter {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
}, to: strURL,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
}
upload.responseJSON
{ response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value
{
print("JSON: \(JSON)")
var dic = response.result.value as? [String: Any]
let alert = UIAlertController(title: "Alert", message: dic!["message"] as? String , preferredStyle: .alert)
self.present(alert, animated: true)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
}))
}
}
case .failure(let error):
print(error)
}
})`
I am using this code, Hope so it helps
func jsonCall(withMultipleImagesImage productImages: [UIImage]?, withfieldName strfieldName: String?, classURL urlClass: String?, witCompilation completion: #escaping (_ Dictionary: [AnyHashable: Any]?, _ error: Error?) -> Void) {
self.AddProgressHud()
//NSError *error;
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: nil)
// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
let BoundaryConstant = "----------V2ymHFg03ehbqgZCaKO6jy"
// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ
let FileParamConstant = strfieldName
// the server url to which the image (or the media) is uploaded. Use your server url here
let url = URL(string: "\(urlBase)\(urlClass ?? "")")
print("url is \(String(describing: url))")
let request = NSMutableURLRequest()
// if userDefaults.value(forKey: userdefaultAuthHeader) != nil {
// //request.setValue(userDefaults.value(forKey: userdefaultAuthHeader) as? String, forHTTPHeaderField: "Authorization")
// }
request.cachePolicy = .reloadIgnoringLocalCacheData
request.httpShouldHandleCookies = false
request.httpMethod = "POST"
// set Content-Type in HTTP header
let contentType = "multipart/form-data;boundary=\(BoundaryConstant)"
request.addValue(contentType, forHTTPHeaderField: "Content-Type")
// request.setValue(contentType, forHTTPHeaderField: "Content-Type")
// post body
let body = NSMutableData()
var count = 0
for image: UIImage in productImages!{
count += 1
let imageData = UIImage.jpegData(image)
//UIImagePNGRepresentation(image)
if imageData != nil {
if let anEncoding = "--\(BoundaryConstant)\r\n".data(using: .utf8) {
body.append(anEncoding)
}
if let anEncoding = ("Content-Disposition: form-data; name=\"\(String(describing: FileParamConstant!))\"; filename=\"image.png\"\r\n ").data(using: .utf8) {
body.append(anEncoding)
}
if let anEncoding = ("Content-Type: image/png\r\n\r\n").data(using: .utf8) {
body.append(anEncoding)
}
// if let aData = imageData {
// body.append(aData)
// }
if let anEncoding = "\r\n".data(using: .utf8) {
body.append(anEncoding)
}
}
}
if let anEncoding = "--\(BoundaryConstant)--\r\n".data(using: .utf8) {
body.append(anEncoding)
}
// setting the body of the post to the reqeust
request.httpBody = body as Data
// set the content-length
//let postLength = "\(UInt((body as Data).count))"
//request.setValue(postLength, forHTTPHeaderField: "Content-Length")
// set URL
request.url = url!
print("re url \(request.url!)")
var postDataTask: URLSessionDataTask?
postDataTask = session.dataTask(with: request as URLRequest) { data, response, error in
if error == nil {
var dicjson: [AnyHashable: Any]? = nil
DispatchQueue.main.async {
// self.hud.hide(animated: true)
}
print("\(String(data: data!, encoding: .utf8) ?? "")")
if let aData = data {
dicjson = try! JSONSerialization.jsonObject(with: aData, options: []) as? [AnyHashable: Any]
}
completion(dicjson, error)
} else {
print("erro \(String(describing: error?.localizedDescription))")
DispatchQueue.main.async {
// self.hud.hide(animated: true)
}
completion(nil, error)
//GlobalClass.showAlertwithTitle("Server Error", message: error?.description)
}
}
postDataTask?.resume()
}
If you are using alammofire then refer this
This question already has answers here:
Upload image with parameters in Swift
(3 answers)
Closed 4 years ago.
Getting HTTP 400 error while connecting with SAP Leonardo sandbox server using scene text recognition API
SAP provides boilerplate code in older version of swift. I have used curl command and the API and works. But its not working when I try and convert the code into swift 4.2 version. I am attaching the code below.
func connectWithSAP(photoURL : URL, photoData : String, sentImageData : Data){
if let myNewURL = URL(string: "https://sandbox.api.sap.com/ml/scenetextrecognition/scene-text-recognition") {
var myRequest = URLRequest(url: myNewURL)
myRequest.addValue("multipart/form-data; --\(boundary)", forHTTPHeaderField: "Content-Type")
myRequest.addValue("application/json", forHTTPHeaderField: "Accept")
myRequest.addValue("xxxxxxxxxxx", forHTTPHeaderField: "APIKey")
myRequest.httpMethod = "POST"
myRequest.cachePolicy = .reloadIgnoringLocalCacheData
myRequest.timeoutInterval = 60.0
// Constructing the body of the request.
var data = Data()
var dataString = ""
dataString.append("--\(boundary)\r\n")
dataString.append(contentsOf: "Content-Disposition:form-data; name=\"files\"; filename=\"Image1.jpeg\" \r\n")
dataString.append(contentsOf: ";Content-Type:image/jpeg \r\n\r\n")
dataString.append(photoData)
dataString.append("--\(boundary) ----- \r\n")
data = dataString.data(using: .utf8)!
myRequest.httpBody = data
let task = URLSession.shared.dataTask(with: myRequest) { (data, response, error) in
if let error = error {
print(error)
}
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode) else {
print(error as Any)
// Getting output at this stage, which is shown below
return }
if let mimeType = httpResponse.mimeType,
mimeType == "application/json",
let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any]
print(json as Any)
}catch {
print(error)
}
}
}
task.resume()
}
I am getting a following details in my response object
{ URL: https://sandbox.api.sap.com/ml/scenetextrecognition/scene-text-recognition } { Status Code: 400, Headers {\n Connection = (\n \"keep-alive\"\n );\n \"Content-Length\" = (\n 131\n );\n \"Content-Type\" = (\n \"application/json\"\n );\n Date = (\n \"Sat, 16 Feb 2019 11:56:37 GMT\"\n );\n Server = (\n \"Werkzeug/0.14.1 Python/3.5.5\"\n );\n \"Strict-Transport-Security\" = (\n \"max-age=31536000; includeSubDomains; preload;\"\n );\n \"X-Vcap-Request-Id\" = (\n \"fea7037c-4e48-49d2-4be1-53b0dad0ee46\"\n );\n}
As you would see the status code is HTTP 400. Need some help in getting the right response and data from the server.
Most probably, the body data got messed up. Here's the working code:
let boundaryConstant = "----WebKitFormBoundary7MA4YWxkTrZu0gW"
let headers = [
"APIKey": "YourAPIKEY"
]
let contentType = "multipart/form-data; boundary=" + boundaryConstant
//API endpoint for API sandbox
var request = URLRequest(url: URL(string: "https://sandbox.api.sap.com/ml/scenetextrecognition/scene-text-recognition")!)
//setting request method
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let path1 = Bundle.main.path(forResource: "your_image", ofType: "png")!
let url = URL(fileURLWithPath: path1)
let fileName = url.lastPathComponent
let data = try? Data(contentsOf: url)
let imageData = UIImage.init(data: data!)!
let pngData = UIImagePNGRepresentation(imageData)!
let mimeType = "image/png"
let boundaryStart = "--\(boundaryConstant)\r\n"
let boundaryEnd = "--\(boundaryConstant)--\r\n"
let fieldName = "files"
let contentDispositionString = "Content-Disposition: form-data; name=\"\(fieldName)\"; filename=\"\(fileName)\"\r\n"
let contentTypeString = "Content-Type: \(mimeType)\r\n\r\n"
var body = Data()
body.append(boundaryStart.data(using: .utf8)!)
body.append(contentDispositionString.data(using: .utf8)!)
body.append(contentTypeString.data(using: .utf8)!)
body.append(pngData)
body.append("\r\n".data(using: .utf8)!)
body.append(boundaryEnd.data(using: .utf8)!)
request.httpBody = body
request.setValue(contentType, forHTTPHeaderField: "Content-Type")
request.setValue(String(body.count), forHTTPHeaderField: "Content-Length")
let dataTask = session.dataTask(with: request) { (data, response, error) in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
}
dataTask.resume()
You can also use Alamofire to upload image. It's way cleaner, don't need to play around with "body" much:
let headers: HTTPHeaders = [
"APIKey": "<<Your API KEY>>",
"Content-type": "multipart/form-data"
]
let parameters:[String: String] = [:] //any other parameters you need to send
let path1 = Bundle.main.path(forResource: "<<your_image>>", ofType: "<<png or jpeg>>")!
let url = URL(fileURLWithPath: path1)
let fileName = url.lastPathComponent
let data = try? Data(contentsOf: url)
let imageData = UIImage.init(data: data!)!
//converting it into png data
let pngData = UIImagePNGRepresentation(imageData)
let mimeType = "image/png"
let fieldName = "files"
Alamofire.upload(multipartFormData: { (multipartFormData) in
for (key, value) in parameters {
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
}
if let data = pngData{
multipartFormData.append(data, withName: fieldName, fileName: fileName, mimeType: mimeType)
}
}, usingThreshold: UInt64.init(), to: "https://sandbox.api.sap.com/ml/scenetextrecognition/scene-text-recognition" , method: .post, headers: headers) { (result) in
switch result{
case .success(let upload, _, _):
upload.responseJSON { response in
print("Succesfully uploaded")
}
case .failure(let error):
print("Error in upload: \(error.localizedDescription)")
}
}
I'm trying to make a call to the OCR.space API by uploading a base 64 image but I keep getting this response:
Not a valid base64 image. The accepted base64 image format is 'data:image/;base64,'
I've checked the image many times to make sure it's encoded properly in base 64 format. Am I setting up the URLRequest properly?
Here is the code:
func extractTextFromImage(_ image: CGImage) {
let bitmapRep = NSBitmapImageRep(cgImage: image)
let imageData = bitmapRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])! as Data
let imageString = imageData.base64EncodedString(options: .endLineWithCarriageReturn)
let url = URL(string: "https://api.ocr.space/parse/image")!
let session = URLSession.shared
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("6ea787d56088957", forHTTPHeaderField: "apikey")
var parameters = ["base64image": [ "content_type": "image/jpeg", "base64": imageString]]
do {
let jsonData = try JSONSerialization.data(withJSONObject: parameters, options: [])
let theJSONText = String(data: jsonData, encoding: String.Encoding.utf8)
print("JSON string = \(theJSONText)")
request.httpBody = jsonData
} catch {
print(error.localizedDescription)
print("ERROR: Could not convert dictionary to JSON")
return
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("6ea787d56088957", forHTTPHeaderField: "apikey")
let task: URLSessionDataTask = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in
if let response = response {
print("RESPONSE: ", response)
} else {
print("ERROR: No response")
}
if let error = error {
print("ERROR: ", error)
} else {
print("No error")
}
do {
let dictionary = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
for (key, value) in dictionary {
print("Key: ", key)
print("Value: ", value)
}
if let parsedResults = dictionary["ParsedResults"] as? [[String: Any]] {
if let parsedResult = parsedResults.first {
if let parsedText = parsedResult["ParsedText"] as? String {
print("PARSED TEXT ", parsedText)
} else {
print("ERROR: Could not read parsedText")
}
} else {
print("ERROR: Could not read first element of parsedResult")
}
} else {
print("ERROR: Could not read parsedResult")
}
} catch let error {
print("ERROR: Could not serialize jSON Data: \(error.localizedDescription)")
}
})
task.resume()
}
After alot of reading and searching, this is the code that I got to work:
///
/// Extracts the text from the given image by placing a call to the OCR.space web api
///
func extractText(from image: CGImage) {
let bitmapRep = NSBitmapImageRep(cgImage: image)
let imageData = bitmapRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])! as Data
let url = URL(string: "https://api.ocr.space/parse/image")!
let session = URLSession.shared
var request = URLRequest(url: url)
request.httpMethod = "POST"
let boundary = "--------69-69-69-69-69"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("6ea787d56088957", forHTTPHeaderField: "apikey")
request.httpBody = createBody(parameters: nil, filePathKey: "file", imageDataKey: imageData, boundary: boundary)
let task = session.synchronousDataTask(urlrequest: request)
let data = task.0
let error = task.2
if data == nil {
print("ERROR: No response from OCR.space api call")
return
}
if error != nil {
print("ERROR: ", error!)
return
}
do {
let dictionary = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
if let parsedResults = dictionary["ParsedResults"] as? [[String: Any]] {
if let parsedResult = parsedResults.first {
if let text = parsedResult["ParsedText"] as? String {
parsedText = text
return
} else {
print("ERROR: Could not read parsedText")
return
}
} else {
print("ERROR: Could not read first element of parsedResult")
return
}
} else {
print("ERROR: Could not read parsedResult")
return
}
} catch let error {
print("ERROR: Could not serialize jSON Data into dictionary: \(error.localizedDescription)")
return
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
///
/// Creates a the body of the url request using the given parameters
///
private func createBody(parameters: [String: String]?, filePathKey: String?, imageDataKey: Data, boundary: String) -> Data {
var body = Data();
if parameters != nil {
for (key, value) in parameters! {
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append("\(value)\r\n".data(using: String.Encoding.utf8)!)
}
}
let filename = "image.jpg"
let mimetype = "image/jpg"
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append(imageDataKey)
body.append("\r\n".data(using: String.Encoding.utf8)!)
body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)
return body
}
This code I use in Upload (I found it in a tutorial) is working successfully but the parameters is not being recognised instead of WHERE emp_name ='(insert employee)'it says emp_name='' because i'm trying to update the URL with the newly uploaded picture. Please help. i'm new to this.
func UploadRequest()
{
let url = URL(string: "http://www.example.com/empupload.php")
let request = NSMutableURLRequest(url: url!)
request.httpMethod = "POST"
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
if (imageDetail.image == nil)
{
return
}
let image_data = UIImagePNGRepresentation(imageDetail.image!)
if(image_data == nil)
{
return
}
let body = NSMutableData()
let loadempname = NSMutableURLRequest()
let fname = "test.png"
let mimetype = "image/png"
let postString = "empName=\(empname.text!))"
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition:form-data; name=\"test\"\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append("hi\r\n".data(using: String.Encoding.utf8)!)
body.append(postString.data(using: String.Encoding.utf8)!)
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition:form-data; name=\"file\"; filename=\"\(fname)\"\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append(image_data!)
body.append("\r\n".data(using: String.Encoding.utf8)!)
body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)
request.httpBody = body as Data
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(
data, response, error) in
guard ((data) != nil), let _:URLResponse = response, error == nil else {
print("error")
return
}
if let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
{
print(dataString)
}
})
task.resume()
}
You can post image through Alamofire multipartFormData in swift3.0. Here is sample code:
let parameters = ["name":"YourName"]
Alamofire.upload(.POST, baseUrl, multipartFormData:
{
multipartFormData in
if let imageData = UIImageJPEGRepresentation(self.imageView.image!, 0.6)
{
multipartFormData.appendBodyPart(data: imageData, name: "keyName", fileName: "photo.jpg", mimeType: "image/jpeg")
}
for (key, value) in parameters
{
if value is String || value is Int
{
multipartFormData.appendBodyPart(data: "\(value)".dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}
}
}, encodingCompletion:
{
encodingResult in
switch encodingResult
{
case .Success(let upload, _, _):
upload.responseJSON { response in
print(response)
if String(response.result) == "SUCCESS"
{
if(response.result.value!.objectForKey("status")) as! String != "fail"
{
// here you can write success case
}
else
{
}
}
else
{
MyLoadingView.dismiss();
MyAlertView.showErrorAlert("Please try Again" )
}
}
case .Failure(let encodingError):
print(encodingError)
}
})
I am trying to upload data to our server. The data is a zip file converted in to Data.
SSZipArchive.createZipFile(atPath: "\(self.currentWPDirectory!)/\(self.documentId!).zip", withFilesAtPaths: checkInFileList)
let zipData = try! Data(contentsOf: URL(string: "file:///\(self.currentWPDirectory!)/\(self.documentId!).zip")!)
URLSession
let parameters = "?documentId=\(self.documentId!)&documentAction=CHECKIN&doc_action_comment=some comment&device_name=\(UIDevice.current.name)"
let urlString = "\(Constants.WebService.checkIn)\(parameters)"
let url = urlString.replacingOccurrences(of: " ", with: "%20")
let request = NSMutableURLRequest(url: URL(string: url)!)
let data = zipData
request.httpMethod = HTTPMethod.post.rawValue
let boundary = "----------SwIfTeRhTtPrEqUeStBoUnDaRy"
let contentType = "multipart/form-data; boundary=\(boundary)"
request.setValue(contentType, forHTTPHeaderField:"Content-Type")
let body = NSMutableData();
let tempData = NSMutableData()
let fileName = "FILE_NAME" + ".zip"
let parameterName = "userfile"
let mimeType = "application/octet-stream"
tempData.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
let fileNameContentDisposition = fileName != "" ? "filename=\"\(fileName)\"" : ""
let contentDisposition = "Content-Disposition: form-data; name=\"\(parameterName)\"; \(fileNameContentDisposition)\r\n"
tempData.append(contentDisposition.data(using: String.Encoding.utf8)!)
tempData.append("Content-Type: \(mimeType)\r\n\r\n".data(using: String.Encoding.utf8)!)
tempData.append(zipData)
tempData.append("\r\n".data(using: String.Encoding.utf8)!)
body.append(tempData as Data)
body.append("\r\n--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
request.setValue("\(body.length)", forHTTPHeaderField: "Content-Length")
request.httpBody = body as Data
let session = URLSession(configuration: URLSessionConfiguration.default)
let task = session.uploadTask(with: request as URLRequest, from: data) { (data, response, err) in
// Gets 206 in response
}
task.resume()
Alamofire
let params = [
"documentId": self.documentId!,
"documentAction": (self.isSync) ? "SYNC" : "CHECKIN",
"doc_action_comment": "Some Comment",
"device_name": UIDevice.current.name
]
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(zipData, withName: "FILE_DATA", fileName: "\(self.documentId!).zip", mimeType: "application/zip")
for (key, value) in params {
multipartFormData.append((value as! String).data(using: .utf8)!, withName: key)
}
},
to: "\(Constants.WebService.checkIn)?documentId=\(self.documentId!)&documentAction=\((self.isSync) ? "SYNC" : "CHECKIN")&doc_action_comment=comment&device_name=\(UIDevice.current.name)",
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
print(response)
// Get 406 Response code
// Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0."
}
self.completionCallback!(true)
}
case .failure(let encodingError):
print(encodingError)
self.completionCallback!(false)
}
}
)
I have tried many ways to get multipart form/data uploads to send my data, with no success. Can anyone point me in the right direction?