有没有办法将我的照片库的最新照片添加到uiimageview?我几乎尝试了一切,但没有任何作用。
答案 0 :(得分:6)
Swift 3
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [SortDescriptor(key: "creationDate", ascending: true)]
let fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)
let last = fetchResult.lastObject
if let lastAsset = last {
let options = PHImageRequestOptions()
options.version = .current
PHImageManager.default().requestImage(
for: lastAsset,
targetSize: imageView.bounds.size,
contentMode: .aspectFit,
options: options,
resultHandler: { image, _ in
DispatchQueue.main.async {
self.imageView.image = image
}
}
)
}
Swift 2
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
let fetchResult = PHAsset.fetchAssetsWithMediaType(.Image, options: fetchOptions)
let last = fetchResult.lastObject
if let lastAsset = last {
let options = PHImageRequestOptions()
options.version = .Current
options.deliveryMode = .HighQualityFormat
PHImageManager.defaultManager().requestImageForAsset(
lastAsset as! PHAsset,
targetSize: imageView.bounds.size,
contentMode: .AspectFit,
options: options,
resultHandler: { image, _ in
dispatch_async(dispatch_get_main_queue(), {
self.imageView.image = image
})
}
)
}
}