iOS Swift + Alamofire upload photos with exif data - ios

I am using Alamofire to upload multiple files at the same time to Open Asset using their REST API and I am able to get this to work, however, most of the EXIF data is being stripped out. Unfortunately, the EXIF data is a must as we need the ability mine out the GPS tags and a few other things through various web clients.
After doing some research, I found the issue is because I'm using UIImageJPEGRepresentation to convert the photos to NSData (which is what Alamofire expects or a fileURL, which I don't think would work for me?).
I am also using the BSImagePicker library to allow the user to take/select multiple photos, which returns a an array of PHAssets which then get converted to NSData. Here is my function to do this (where collectedImages is a global dictionary):
func compressPhotos(assets: [PHAsset]) -> Void {
for asset in assets {
let filename = self.getOriginalFilename(asset)
let assetImage = self.getAssetPhoto(asset)
let compressedImage = UIImageJPEGRepresentation(assetImage, 0.5)! // bye bye metadata :(
collectedImages[filename] = compressedImage
print("compressed image: \(filename)")
}
}
I think I could retain the EXIF data if I could use the full path from the PHAsset to the image locally on the phone, but Alamofire does not appear to support that. I'm hoping I'm wrong about that. Here is my uploader:
func uploadPhotos(projectId: String, categoryId: String, data: [String: NSData], completionHandler: (AnyObject?, NSError?) -> ()) {
var jsonBody = [AnyObject]() //lazy
Alamofire.upload(
.POST,
self.url + "/Files",
multipartFormData: { multipartFormData in
for (filename, img) in data {
jsonBody.append(["project_id": projectId, "category_id": categoryId, "original_filename": filename])
multipartFormData.appendBodyPart(data: img, name: "file", fileName: filename, mimeType: "image/jpeg")
print("img size: \(img.length)")
}
let jsonData = jsonToNSData(jsonBody)
print("_jsonBody: \(jsonBody)")
multipartFormData.appendBodyPart(data: jsonData!, name: "_jsonBody")
print("multipart: \(multipartFormData)")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
switch response.result {
case .Success(let value):
completionHandler(value as? NSArray, nil)
case .Failure(let error):
completionHandler(nil, error)
}
}
case .Failure(let encodingError):
print(encodingError)
}
}
)
}
So my question is, how can I upload multiple photos (while passing in other parameters too) while maintaining all the EXIF data? Alamofire is an awesome library and I would like to use it here, but I'm not married to it for the upload process if I can't keep the EXIF data.

I think you can first get the file URL from the PHAsset then use that file URL in the call to multipartFormData.appendBodyPart(...). Something like this:
Get URL from PHAsset:
[asset requestContentEditingInputWithOptions:editOptions
completionHandler:^(PHContentEditingInput *contentEditingInput, NSDictionary *info) {
NSURL *imageURL = contentEditingInput.fullSizeImageURL;
}];
Use file URL in AlamoFire API:
multipartFormData.appendBodyPart(fileURL: imageURL, name: "image")

I am not sure why I was having issues with the fullSizeImageURL, but I it did lead me to the right path as I was able to get this to work by getting the image as NSData from the file path like this:
asset.requestContentEditingInputWithOptions(PHContentEditingInputRequestOptions()) { (input, _) in
let fileURL = input!.fullSizeImageURL?.filePathURL
let data = NSData(contentsOfFile: fileURL!.path!)!
And then I just passed that in the Alamofire.request() as the data argument. This maintained all the original photo metadata.

Related

Uploading multiple images with Alamofire causes huge memory usage

I am working on an app that we need to upload multiple images to our server using Alamofire. The problem is converting UIImage to Data then appending it to Multipart uses so much memory and eventually causes app to crash.
Alamofire.upload(multipartFormData: { (multipart) in
for (key, value) in endpoint.params {
if let images = value as? [UIImage] {
for i in 0..<images.count {
if let data = UIImageJPEGRepresentation(images[i], 0.6) {
multipart.append(data, withName: "\(key)\(i)", fileName: "note.jpg", mimeType: "image/jpeg")
}
}
}
}
}, usingThreshold: UInt64.init(),
to: endpoint.path,
method: endpoint.method,
headers: endpoint.headers,
encodingCompletion: {...}
Some people advised using a stream but couldn't find an example. How can I fix the issue?

iOS Swift uploading PDF file with Alamofire (Multipart)

I'm currently developing an application using iOS 10 and Swift 3 and Alamofire 4
The purpose of this application is to upload a PDF file generated previously.
The PDF generation is working perfectly and the file is created.
However the upload doesn’t work…
I received a success response but the file is not uploaded.
My server response
Multi part Content-Type => multipart/form-data; boundary=alamofire.boundary.56958be35bdb49cb
Multi part Content-Length => 293107
Multi part Content-Boundary => alamofire.boundary.56958be35bdb49cb
responses
SUCCESS: {
uploadedFiles = (
{
details = " Key=Content-Disposition - values=[form-data; name=\"pdfDocuments\"] length=8";
storedFileName = "/var/www/pdf/17/009/22/TMP104150531290406.tmp";
type = PDF;
uploadedDate = 1483999296701;
uploadedFileName = UnknownFile;
}
);
}
end responses
I’m using multi-part to upload my file as Data as you can see here
File url is fine.
I have searched on SO but didn’t find any solution working…
Here you can see my Controller
Alamofire.upload(
multipartFormData: {
multipartFormData in
if let urlString = urlBase2 {
let pdfData = try! Data(contentsOf: urlString.asURL())
var data : Data = pdfData
multipartFormData.append(data as Data, withName:"test.pdf", mimeType:"application/pdf")
for (key, value) in body {
multipartFormData.append(((value as? String)?.data(using: .utf8))!, withName: key)
}
print("Multi part Content -Type")
print(multipartFormData.contentType)
print("Multi part FIN ")
print("Multi part Content-Length")
print(multipartFormData.contentLength)
print("Multi part Content-Boundary")
print(multipartFormData.boundary)
}
},
to: url,
method: .post,
headers: header,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
print(" responses ")
print(response)
print("end responses")
onCompletion(true, "Something bad happen...", 200)
}
case .failure(let encodingError):
print(encodingError)
onCompletion(false, "Something bad happen...", 200)
}
})
Thanks in advance for the help.
Regards
I have just found my solution to fix this bug.
I have forgot a parameter for the file name.
multipartFormData.append(pdfData, withName: "pdfDocuments", fileName: namePDF, mimeType:"application/pdf")
Thanks for the help.

Using Alamofire and multipart/form-data

I'm unable to approach the API that has been offered to me in the proper way for it to give me the response I'm looking for. I've been using Swift and Alamofire for a while but this is the first time I've to upload images using multipart/form-data. I'm able to upload images using Postman but I'm unable to get the same message send out by my application using the Alamofire framework.
My Swift code:
func postFulfilWish(wish_id: Int, picture : UIImage, completionHandler: ((AnyObject?, ErrorType?) -> Void)) {
var urlPostFulfilWish = Constant.apiUrl;
urlPostFulfilWish += "/wishes/";
urlPostFulfilWish += String(wish_id);
urlPostFulfilWish += "/fulfill/images" ;
let image : NSData = UIImagePNGRepresentation(UIImage(named: "location.png")!)!
Alamofire.upload(.POST, urlPostFulfilWish, headers: Constant.headers, multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: image, name: "file")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
//This is where the code ends up now
//So it's able to encode my message into multipart/form-data but it's not doing it in the correct way for the API to handle it
debugPrint(response)
}
case .Failure(let encodingError):
print(encodingError)
}
}
)
}
In case it is not already answered, recently I had the same problem using Alamofire to upload an Image using form-data.
I was able to upload the image using Postman exactly as it's shown in this post, but no able to do it using Alamofire in my app.
You need to check two things, first of all, the name of the file that the server is expecting, and second the method used to append the body part in the multipartFormData closure.
This two methods were not working in my case -
multipartFormData.appendBodyPart(data: imageData, name: "file")
this one neither
multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: name)
But on this one worked splendid -
multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "file.jpeg", mimeType: "image/jpeg")
The problem basically is that the server can't find the file with the expected name.
I hope this help someone to save time wondering why it's not working.
You are doing debugPrint(response). You presumably should do another switch response.result { ... } and see if you got .Success or .Failure as the result of the request, and if success, you'd look at the response object contents (or if failure, look at the failure error). You need to look at that result to diagnose whether it was successful or not.
Alamofire.upload(.POST, urlPostFulfilWish, headers: Constant.headers, multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: image, name: "file")
}) { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
switch response.result {
case .Success(let value):
print(value)
case .Failure(let error):
print(error)
}
}
case .Failure(let encodingError):
print(encodingError)
}
}
I recently got a 404 from the server when posting a multipart request along with parameters in the body. I was using a UIImagePickerController (the delegate for which returns a UIImage) and I then sent up the PNG representation of it.
This only occurred for files that were JPEG on disk. Strangely this issue seems to only affect multipart requests that also had parameters in the body. It worked fine when the API endpoint didn't require anything else.
My guess is that there is something weird going on along the line of JPEG -> UIImage -> PNG representation that results in some sort of problem which oddly only seems to manifest itself in multipart requests that also have parameters in the body. Might be some special characters in there that makes the server not recognise the request and just return a 404.
I ended up fixing it by sending up the UIImageJPEGRepresentation of the selected image instead of UIImagePNGRepresentation, and no such errors.
I believe the question is outdated already but for as long as there is no answer accepted try the following:
multipartFormData.appendBodyPart(data: imageData, name: "name", fileName: "filename", mimeType: mimeType)

Uploading files with Alamofire and Multer

I'm trying to upload image data from iOS using Alamofire to an Express server with Multer. req.file is undefined, and req.body is in the form { file: <bytes> }. There is no error message, but the file does not appear. Here is my code:
var bodyParser = require('body-parser')
var multer = require('multer')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.post('/api/photos/upload', function(req, res) {
var upload = multer({ dest: 'public/images/content/'}).single('file')
upload(req, res, function(err) {
if (err) {
console.log("Error uploading file: " + err)
return
}
// req.file = req.body
console.log(req.body) // form fields
console.log(req.file) // form file
})
res.json('yeah')
})
On iOS:
let url = fullURL("api/photos/upload")
Alamofire.upload(.POST, url, multipartFormData: { multipartFormData in
if let image = image {
if let imageData = UIImageJPEGRepresentation(image, 0.5) {
multipartFormData.appendBodyPart(data: imageData, name: "file")
}
}
}, encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
switch response.result {
case .Success:
print("success")
case .Failure(let error):
print(error)
}
}
case .Failure(let encodingError):
print(encodingError)
}
})
This has puzzled me for hours, any help is greatly appreciated!
UPDATE
An HTML form worked fine through the Express endpoint, so it's definitely a problem with the request Alamofire is sending. I've tried a bunch of examples of uploading with Alamofire, but they all send the same incorrect request. There must be a way to make the same request as an HTML form but with Alamofire.
ANOTHER UPDATE
I'm now just using busboy-connect and it's working well, and with a lot more flexibility.
I was just able to get this working. It turns out that you have to specify the fileName and the mimeType using Alamofire in order for multer to pick up the upload on the server end. So, your code for adding the image should look something like this:
if let image = image {
if let imageData = UIImageJPEGRepresentation(image, 0.5) {
multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "fileName.jpg", mimeType: "image/jpeg")
}
}
Your issue is likely caused by not using multer as a middleware:
var upload = multer({ dest: 'public/images/content/'})
app.post('/api/photos/upload', upload.single('file'), function(req, res) {
// req.file should be populated now
})
In express, you can add as many middlewares as you need:
app.post('/path',
middleware1,
middleware2,
middleware3,
...,
function(req, res) {
// All middlewares has been executed
})
you know, there is difference between the method multipartFormData.append(value.data, withName: name, fileName: filename, mimeType: mimeType) and multipartFormData.append(value.data, withName: key).
when you use the former, multer will take it as req.file、the latter as req.body.

Deadlock inside NSURLSession delegate queue

I'm experiencing a deadlock inside one of the operations in the NSUrlSession delegate queue when using Alamofire.
it happens when i'm doing at least one download and one upload simultaneously (all requests are done through the default Alamofire manager). Is there any problem doing so from multiple threads? (either in NSUrlSession or Alamofire)
it seems to be stuck on __psynch_mutexwait in one of the operations in the NSURLSession delegate queue, and it completely shuts down the app's ability to make network requests through Alamofire (because the delegate won't be called ever).
as I said the download and upload called simultaneously on 2 different queues (one of them is usually called on the main thread)
upload example :
Alamofire.upload(.POST, uploadURL,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: x.dataUsingEncoding(NSUTF8StringEncoding)!, name: "X")
multipartFormData.appendBodyPart(data: fileData, name: "file", fileName: "Y", mimeType: "application/octet-stream")
}
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.response { (request, response, data, error) -> Void in
if let error = error {
callback("Failure", "\(error)")
} else {
callback("SUCCESS", nil)
}
}
case .Failure(let encodingError):
callback(nil, "Failed due to \(encodingError)")
}
}
)
download example :
Alamofire.download(.GET, downloadUrl, parameters: ["a": "a", "b": "b"], destination:
{
tempURL, response in
return path
}).response {
(request, response, _, error) in
let data = NSData(contentsOfURL: path)
doSomeStuffWithDownloadedData(data)
// make another request after download completed
Alamofire.request(.GET, requestUrl, parameters: ["c":"c", "d":"d"]).response {
request, response, data, error in
if let e = error {
log.error("request failed, \(e)")
}
}
}
stack trace
After commenting most of my code I isolated the code causing the problem and it does not related at all to alamofire or NSURLSession.
I have in my own code a call to objc_sync_enter on an array (of objects), it always has a matching objc_sync_exit call on the same array. after changing this call to be on self instead of this array, the deadlock inside NSBlockOperation is gone. It may be related to the fact that an array is not an object but a struct. So if you experience very strange deadlock in your code, I suggest that before you try anything else, make sure you don't have calls of objc_sync_enter on structs.

Resources