版本 XCode8.3,swift 3.1
在写一个9宫格选择器的时候,从相册选取没什么大的问题,但是从相机选取时出现问题,因为我计划是拿到PHAsset对象(不是直接拿UIImage对象),放入数据源,通过查资料和以往的经验以及查看PHAsset库方法,发现
open class func fetchAssets(withALAssetURLs assetURLs: [URL], options: PHFetchOptions?) -> PHFetchResult<PHAsset>
,也因此入坑,想通过UIImagePickerControllerReferenceURL
拿到ALAssetURL,但是发现始终为 nil,经过分析(百度)和测试(stackover),发现当UIImagePickerControllerType.camera的时候,就是没有UIImagePickerControllerReferenceURL,大概是因为此时还没有存储到本地,so~,看代码,核心代码如下:
新接触swift,语法有问题的尽量提哈,
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
// 设置筛选条件
let allPhotosOptions = PHFetchOptions()
// 按图片生成时间排序
allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
//选择普通照片
allPhotosOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)
//本地路径,代替ReferenceURL
var localIdentifier: String = ""
//通过存储图片到本地路径,顺便拿到Url
PHPhotoLibrary.shared().performChanges({
//
let createdAssetID = PHAssetChangeRequest.creationRequestForAsset(from: image).placeholderForCreatedAsset?.localIdentifier
localIdentifier = createdAssetID!
print("createdAssetID:\(createdAssetID ?? "nil")")
}) { (success, error) in
//通过localIdentifier 拿到PHAsset对象
let assets = PHAsset.fetchAssets(withLocalIdentifiers: [localIdentifier], options: allPhotosOptions)
if assets.firstObject != nil
{
//这里拿到了PHAsset对象,往下操作就看自己的需求了
self.dataSource.insert(assets.firstObject!, at: self.dataSource.count - 1)
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
}
picker.dismiss(animated: true) {
//
}
}