问题
I am facing a really weird problem. I am trying to pick an image and upload the same after cropping it, to the server. I am unable to do it on my iphone 5s running on ios 11.0.3. But the same is working fine on iphone 5 which is running ios 10.3.3.
I am using the following code to pick the image from gallery:
func showImgPicker()
{
self.imagePicker.allowsEditing = false
self.imagePicker.sourceType = .photoLibrary
self.present(self.imagePicker, animated: true, completion: nil)
}
@IBAction func getImgs(_ sender: UIButton) {
let photos = PHPhotoLibrary.authorizationStatus()
if photos == .notDetermined {
PHPhotoLibrary.requestAuthorization({status in
if status == .authorized{
self.showImgPicker()
} else {
}
})
}
else
{
showImgPicker()
}
}
@objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let imageURL = info[UIImagePickerControllerReferenceURL] as! NSURL
picker.dismiss(animated: true, completion: nil)
dismiss(animated: true) {
self.delegate?.presentEditor(img: (info[UIImagePickerControllerOriginalImage] as? UIImage)!, id: self.id!, type: self.commentType)
}
}
And once the image is picked, I am sending it for copping, post that the image is being saved in the local document directory of the app:
static func SaveImgLocal(img: UIImage, tsStr: String) -> String
{
let fileManager = FileManager.default
do {
let documentDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:false)
let fileURL = documentDirectory.appendingPathComponent("\(tsStr).jpeg")
if let imageData = UIImageJPEGRepresentation(img, 1) {
try imageData.write(to: fileURL)
return "\(tsStr).jpeg"
}
else
{
return Constants.MESSAGE_ERROR
}
} catch {
return Constants.MESSAGE_ERROR + " " + error.localizedDescription
}
}
And finally I am uploading the image to the server:
let url2 = URL(string: "file:///private\((url?.absoluteString)!)")
print(url2)
print(url)
let salesObj = try SalesFactory.getSalesService()
try uploadDoc(url: Urls.uploadImgUrl, docUrl: url2!, parseResponse: { (result) in
print(result)
}
public static func uploadDoc(url: String, docurl: URL, httpResponse: @escaping (DataResponse<Any>) -> Void) throws
{
let hdr: HTTPHeaders = ["Accept": "application/json"]
Alamofire.upload(docurl, to: url, method: .post, headers: hdr).responseJSON { (response) in
print(response)
httpResponse(response)
}
}
The same code works on ios 10.3.3 but not on ios 11.0.3. There are no errors. The server sends a message mentioning upload failed.
回答1:
Added NSPhotoLibraryAddUsageDescription in info.plist and compressed the image. Its started working.
Anyone facing this problem, please add both NSPhotoLibraryUsageDescription and NSPhotoLibraryAddUsageDescription in info.plist.
来源:https://stackoverflow.com/questions/46882548/unable-to-upload-images-in-ios-11-0-3