![](/img/trans.png)
[英]How to get an authorized PHAsset from UIImagePickerController?
[英]How to retrieve PHAsset from UIImagePickerController
我正在嘗試檢索 PHAsset,但是 PHAsset.fetchAssets(withALAssetURLs:options:) 已從 iOS 8 中棄用,因此如何正確檢索 PHAsset?
我遇到了同樣的問題,首先檢查權限並請求訪問:
let status = PHPhotoLibrary.authorizationStatus()
if status == .notDetermined {
PHPhotoLibrary.requestAuthorization({status in
})
}
只需將其連接到觸發 UIImagePickerController 的任何內容即可。 委托調用現在應該在 userInfo 中包含 PHAsset。
guard let asset = info[UIImagePickerControllerPHAsset] as? PHAsset
這是我的解決方案:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if #available(iOS 11.0, *) {
let asset = info[UIImagePickerControllerPHAsset]
} else {
if let assetURL = info[UIImagePickerControllerReferenceURL] as? URL {
let result = PHAsset.fetchAssets(withALAssetURLs: [assetURL], options: nil)
let asset = result.firstObject
}
}
}
除非用戶已授權,否則 PHAsset 不會出現在didFinishPickingMediaWithInfo: info
結果中,這對我來說並沒有發生,只是通過呈現選擇器。 我在 Coordinator init() 中添加了這個:
let status = PHPhotoLibrary.authorizationStatus()
if status == .notDetermined {
PHPhotoLibrary.requestAuthorization({status in
})
}
我不確定你想要什么。
您是否嘗試以 iOS 8 為目標?
這就是我獲取照片的方式,它適用於iOS(8.0 及更高版本)、macOS(10.11 及更高版本)、tvOS(10.0 及更高版本)。 代碼在可能令人困惑的地方進行了注釋
第二個函數實際上會獲取它們
//import the Photos framework import Photos //in these arrays I store my images and assets var images = [UIImage]() var assets = [PHAsset]() fileprivate func setPhotoOptions() -> PHFetchOptions{ let fetchOptions = PHFetchOptions() fetchOptions.fetchLimit = 15 let sortDescriptor = NSSortDescriptor(key: "creationDate", ascending: false) fetchOptions.sortDescriptors = [sortDescriptor] return fetchOptions } fileprivate func fetchPhotos() { let allPhotos = PHAsset.fetchAssets(with: .image, options: setPhotoOptions()) DispatchQueue.global(qos: .background).async { allPhotos.enumerateObjects({ (asset, count, stop) in let imageManager = PHImageManager.default() let targetSize = CGSize(width: 200, height: 200) let options = PHImageRequestOptions() options.isSynchronous = true imageManager.requestImage(for: asset, targetSize: targetSize, contentMode: .aspectFit, options: options, resultHandler: { (image, info) in if let image = image { self.images.append(image) self.assets.append(asset) } if count == allPhotos.count - 1 { DispatchQueue.main.async { //basically, here you can do what you want //(after you finish retrieving your assets) //I am reloading my collection view self.collectionView?.reloadData() } } }) }) }
}
根據OP的說明進行編輯
您需要設置委托UIImagePickerControllerDelegate
然后實現以下功能
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
在所述方法中,獲取如下圖像:
var image : UIImage = info[UIImagePickerControllerEditedImage] as! UIImage
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.