我尝试通过imagePickerController(iOS,swift 3)添加图片的路径,我尝试了不同的方法,但每次都得到“nil”......
这就是我尝试的方式:
1
if let picturePath = info[UIImagePickerControllerReferenceURL] as? URL {
print(picturePath)
} else {
print("Oh no...")
}
2
let imageURL = info[UIImagePickerControllerReferenceURL] as NSURL
let imageName = imageURL.path!.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as String
let localPath = documentDirectory.stringByAppendingPathComponent(imageName)
和3.
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
let imageUrl = info[UIImagePickerControllerReferenceURL] as? NSURL
let imageName = imageUrl?.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let photoURL = NSURL(fileURLWithPath: documentDirectory)
let localPath = photoURL.appendingPathComponent(imageName!)
if !FileManager.default.fileExists(atPath: localPath!.path) {
do {
try UIImageJPEGRepresentation(image, 1.0)?.write(to: localPath!)
print("file saved")
}catch {
print("error saving file")
}
}
else {
print("file already exists")
}
如果您有任何想法,我会很高兴听到它!
谢谢,
亚历山大。
答案 0 :(得分:1)
如果您添加图片(即使用相机拍摄),则不会自动保存。通过访问info[UIImagePickerControllerOriginalImage]
,您只能获得UIImage。
您可以使用UIImageWriteToSavedPhotosAlbum(_:_:_:_:)
将其保存到相机胶卷或获取JPEG representation并将返回的Data
保存在文档文件夹中的任何位置(例如#3,但你必须自己想出一个文件名。)
<强>更新强>
好的,这是它的工作原理。只是强调这一点:在图像选择器完成处理程序中,您只获得UIImage
。此图片尚未保存,因此无法获取网址。
然后你可以
completionSelector
的{{1}}仅告诉您它是否有效或是否发生错误。UIImageWriteToSavedPhotosAlbum(...)
为了简化,我选择了一个UUID作为(基本)文件名。
您告诉照片库创建资产,然后查询该资产以获取该URL。为简洁起见,我省略了错误处理。
func saveToDocuments(image: UIImage) -> URL throws
{
let imageFolder = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let imageURL = imageFolder.appendingPathComponent("\(UUID()).jpg")
let jpegData = UIImageJPEGRepresentation(image, 0.5)
try jpegData?.write(to: imageURL, options: .atomic)
return imageURL
}
用法:
func saveToCameraRoll(image: UIImage, completion: @escaping (URL?) -> Void) {
var placeHolder: PHObjectPlaceholder? = nil
PHPhotoLibrary.shared().performChanges({
let creationRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
placeHolder = creationRequest.placeholderForCreatedAsset!
}, completionHandler: { success, error in
guard success, let placeholder = placeHolder else {
completion(nil)
return
}
let assets = PHAsset.fetchAssets(withLocalIdentifiers: [placeholder.localIdentifier], options: nil)
guard let asset = assets.firstObject else {
completion(nil)
return
}
asset.requestContentEditingInput(with: nil, completionHandler: { (editingInput, _) in
completion(editingInput?.fullSizeImageURL)
})
})
}
答案 1 :(得分:0)
是的,我知道,但在尝试获取图片的路径之前,我保存了图片:
let img = info[UIImagePickerControllerOriginalImage] as? UIImage
UIImageWriteToSavedPhotosAlbum(img!, nil, nil, nil)
然后我试着找到路径......
我的#3,我收到了这个错误:
fatal error: unexpectedly found nil while unwrapping an Optional value