I'm trying to send an image (taken from the user using UIImagePickerController), to an API that is looking for a physical file. Either JPEG or PNG will do... Using this code...how do I format it to be sent?
My POST function... The "(image variable)" in the postString should be the image file...
var request = URLRequest(url: URL(string: "web address.php")!)
request.httpMethod = "POST"
let postString = "action=setDefendentData&username=\("\(userNameString!)")&datetime=\(localDate)&latitude=\(latitude!)&longitude=\(longitude!)&image=\(image variable)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
OperationQueue.main.addOperation{
loginAlertPopup(title: "Error", message: "Invalid Source: Check Internet Connection")
}
// check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
if responseString! == "success" {
print("Good")
// Success Alert \\
self.presentAlert(title: "Success", message: "Check-In has been updated!")
}
if responseString! == "fail" {
print("failed sending image")
print("Post String: \(postString)")
// Alert Error \\
OperationQueue.main.addOperation{
self.presentAlert(title: "Error", message: "Failed Sending Data")
}
}
}
task.resume()
}
This is my code for saving the image to data using UIImagePickerController:
let fileDirectory : NSURL = {
return try! FileManager.default.url(for: .documentDirectory , in: .userDomainMask , appropriateFor: nil, create: true)
}() as NSURL
let imageQuality: CGFloat = 0.5
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
// Saves to App Data
let imagePath = fileDirectory.appendingPathComponent("uploadImage.jpg")
guard let imageData = UIImageJPEGRepresentation(image, imageQuality) else {
// handle failed conversion
presentAlert(title: "Error", message: "Image Failure")
print("jpg error")
return
}
try! imageData.write(to: imagePath!)
print("Image Path: \(imagePath!)")
print("Image Size: \(imageData)")
//Get Image
let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
if let dirPath = documentPath.first{
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("uploadImage.jpg")
let newImage = UIImage(contentsOfFile: imageURL.path)
I've tried sending through the image
variable (newImage
in this case) and it doesn't accept it. Ive created a temporary UIImageView on my view controller to display newImage
and it updates accordingly... The API handler just doesn't accept it.
Any info/help please?