我試圖發送一個圖像(從用戶使用UIImagePickerController),到一個正在尋找物理文件的API。 JPEG或PNG都可以...使用此代碼...我如何格式化它以發送?通過HTTPS POST發送圖像?
我的POST功能......的「(圖像變量)」中的postString應該是圖像文件...
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()
}
這是我的代碼保存使用的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)
我試過發送通過image
變量(在這種情況下爲newImage
),它不接受它。我在我的視圖控制器上創建了一個臨時UIImageView來顯示newImage
,並相應地進行了更新... API處理程序不接受它。
任何信息/幫助嗎?
http://stackoverflow.com/questions/16434537/post-image-to-server-in-iphone圖像 –