我从照片库中无法获取图像名称。 这里有人知道一种正确的方法来获取图像名称吗?
注意:PHAsset.fetchAssets(withALAssetURLs: [imageURL], options: nil)
已经过时。
仅适用于Swift编程语言
谢谢
我从照片库中无法获取图像名称。 这里有人知道一种正确的方法来获取图像名称吗?
注意:PHAsset.fetchAssets(withALAssetURLs: [imageURL], options: nil)
已经过时。
仅适用于Swift编程语言
谢谢
if let asset = info["UIImagePickerControllerPHAsset"] as? PHAsset{
if let fileName = asset.value(forKey: "filename") as? String{
print(fileName)
}
}
您是指图像文件名吗?如果是,这应该可以帮助您。在您的UIImagePickerControllerDelegate中:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
guard let fileUrl = info[UIImagePickerControllerImageURL] as? URL else { return }
print(fileUrl.lastPathComponent)
}
iOS 12、Swift 4更新:
这将直接为您提供文件名和文件扩展名
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
guard let fileUrl = info[UIImagePickerController.InfoKey.imageURL] as? URL else { return }
print(fileUrl.lastPathComponent) // get file Name
print(fileUrl.pathExtension) // get file extension
dismiss(animated: true, completion: nil)
}
请尝试以下代码
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let asset = info[UIImagePickerControllerPHAsset] as? PHAsset {
if let fileName = (asset.value(forKey: "filename")) as? String {
print(\(fileName))
}
}
// Other Stuff
}
UIImagePickerControllerPHAsset
如果您没有获得访问照片库的权限,它将会是nil
。操作系统不会自动询问并仍然会给您访问该文件的权限(我不知道背后的逻辑!),但是在信息字典中的PHAsset
将会是nil
!
正确的做法是:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
var imageName = "image_1"
if let asset = info[.phAsset] as? PHAsset, let fileName = asset.value(forKey: "filename") as? String {
imageName = fileName
} else if let url = info[.imageURL] as? URL {
imageName = url.lastPathComponent
}
}
PHAsset
如果用户没有授权您的应用程序访问库,则将为nil
。如果您使用默认的UIImagePickerController
,则不再需要此权限,因此,如果您的应用程序没有获得此权限,操作系统将为您提供对图像副本的临时访问权限,您只能回退到路径URL。
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let asset = info[UIImagePickerControllerPHAsset] as? PHAsset {
let assetResources = PHAssetResource.assetResources(for: asset)
print(assetResources.first!.originalFilename)
}
dismiss(animated: true, completion: nil)
}