问题描述
这是我尝试的代码
public func imagePickerController(_ picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
guard let image = info[.editedImage] as? UIImage else {
return self.pickerController(picker,didSelect: nil)
}
if let asset: PHAsset = info[UIImagePickerController.InfoKey.phAsset] as? PHAsset {
print("Asset: \(asset)")
print("Creation Data \(String(describing: asset.creationDate))")
print("Location: \(String(describing: asset.location))")
print("burstIdentifier: \(String(describing: asset.burstIdentifier))")
print("burstSelectionTypes: \(String(describing: asset.burstSelectionTypes))")
print("duration: \(String(describing: asset.duration))")
print("mediaSubtypes: \(String(describing: asset.mediaSubtypes))")
print("mediaType: \(String(describing: asset.mediaType))")
print("pixelHeight: \(String(describing: asset.pixelHeight))")
print("pixelWidth: \(String(describing: asset.pixelWidth))")
print("sourceType: \(String(describing: asset.sourceType))")
} else {
print("Asset: nil")
}
self.pickerController(picker,didSelect: image)
}
注意: 我也尝试使用PHAsset,但始终返回nil。 还可以找到一些建议,但是所有建议都已弃用。
解决方法
您需要先将图像存储在PHAsset中,然后才能获得资产对象。
if let originalImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
self.getAssetAfterStoreImage(image: originalImage) { (assetInstance) in
//asset
print(assetInstance)
}
}
}
func getAssetAfterStoreImage(image:UIImage,completion:@escaping (PHAsset) -> Void){
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAsset(from: image)
}) { saved,error in
if saved {
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate",ascending: true)]
// After uploading we fetch the PHAsset for most recent video and then get its current location url
if let fetchResult = PHAsset.fetchAssets(with:.image,options: fetchOptions).lastObject{
completion(fetchResult)
}
}
}
}
请让我知道是否有任何疑问。
,您的代码很好。只需授予“相机”应用的位置权限
这是授予权限的步骤。
设置应用->隐私->定位服务(第一个选项)->相机->选择选项使用应用时
您的代码输出
Asset: <PHAsset: 0x114d25100> BE7D9140-3D8D-4EAC-8D1F-F97991A9E1EF/L0/001 mediaType=1/0,sourceType=1,(2448x3264),creationDate=2020-10-22 06:26:50 +0000,location=1,hidden=0,favorite=0
Creation Data Optional(2020-10-22 06:26:50 +0000)
Location: Optional(<+23.043114450,+72.6401118833> +/- 0.00m (speed 0.00 mps / course 95.04) @ 01/01/01,5:30:00 AM India Standard Time)
burstIdentifier: nil
burstSelectionTypes: PHAssetBurstSelectionType(rawValue: 0)
duration: 0.0
mediaSubtypes: PHAssetMediaSubtype(rawValue: 0)
mediaType: PHAssetMediaType
pixelHeight: 3264
pixelWidth: 2448
sourceType: PHAssetSourceType(rawValue: 1)