我正在尝试使用其网址在另一个视图中显示本地库中的图像,如此...
let myImgObj = messagesFromTheDisk[indexPath.row].images
print(myImgObj)
print(myImgObj[0].url)
打印myImgObj
提供[MyApp.ProductImage(url: assets-library://asset/asset.PNG?id=A636DA16-8C7C-4CC5-ADB3-E944DC24BDA1&ext=PNG)]
,打印myImgObj[0].url
提供assets-library://asset/asset.PNG?id=A636DA16-8C7C-4CC5-ADB3-E944DC24BDA1&ext=PNG
但是当我尝试显示此图像时,它显示为null虽然似乎有一个网址。我正在使用库SDWebImage
来显示图像......
cell.productImageView.sd_setImage(with: myImgObj[0].url, placeholderImage:UIImage(named: "sampleImg"))
我做错了什么......?
答案 0 :(得分:1)
这没有SDWebImage,因为我不需要PHAssets。我从我的自定义相册中获取库中的assests:
func fetchCustomAlbumPhotos( completion : (_ array : [PHAsset]) -> Void)
{
var assetCollection = PHAssetCollection()
var photoAssets = PHFetchResult<AnyObject>()
var arrayOfPHAsset = [PHAsset]()
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", CustomAlbum.albumName)
let collection:PHFetchResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
if let _:AnyObject = collection.firstObject{
assetCollection = collection.firstObject!
}else {
completion([])
}
_ = collection.count
photoAssets = PHAsset.fetchAssets(in: assetCollection, options: nil) as! PHFetchResult<AnyObject>
photoAssets.enumerateObjects({(object: AnyObject!,
count: Int,
stop: UnsafeMutablePointer<ObjCBool>) in
if object is PHAsset{
let asset = object as! PHAsset
arrayOfPHAsset.append(asset)
}
})
completion(arrayOfPHAsset)
}
这是我在ViewController的viewDidLoad()方法中调用它的方式:
CustomAlbum().fetchCustomAlbumPhotos { (array) in
self.arrayOfPHAsset = array
self.collectionView.reloadData()
}
从该函数我得到arrayOfPHAsset,这就是我在我的集合视图中显示它们的方法:cellForItemAt方法:
let asset : PHAsset = arrayOfPHAsset[indexPath.item]
或将您的网址转换为PHAsset
self.imageURL = (info[UIImagePickerControllerReferenceURL] as? NSURL)!
let asset = PHAsset.fetchAssetsWithALAssetURLs([imageUrl], options: nil).firstObject as! PHAsset
请求该PHAsset的图像
if asset.mediaType == .video{
cell.videoIndicatorImage.isHidden = false
}
cell.userImagesStoredInAlbum.alpha = 0
let imageSize = CGSize(width: asset.pixelWidth,height: asset.pixelHeight)
DispatchQueue.main.async {
PHImageManager.default().requestImage(for: asset, targetSize: imageSize, contentMode: .aspectFill, options: nil, resultHandler: {(result, info)in
if result != nil {
cell.userImagesStoredInAlbum.image = result
UIView .animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
cell.userImagesStoredInAlbum.alpha = 1
}, completion: { (succes) in
})
}
})
}
答案 1 :(得分:0)
我设置图片libary url nil并使用contentsOfFile来捕获磁盘中的图像,以便立即加载图像并且它可以正常工作。但是你必须将图像放在.xcassettes文件夹中而是单独的一组文件夹中。
let bundlePath = Bundle.main.path(forResource: myImgObj, ofType: "jpg")
imageView.sd_setImage(with: nil, placeholderImage: UIImage(contentsOfFile: bundlePath!))