PHAsset library has deprecated in iOS9, and Apple introduces new framework ‘Photos Framework’ for retrieve assets for display and playback, edit image or video content, or work with collections of assets such as album, moments, and iCloud Shared Album.
The first thing you need to do is to fetch the asset or assets. You can choose between either collecting one asset (photo or video), a collection of them, all assets of a certain media type or a media with a certain identifier or URL.
It is important to remember that this class won’t fetch the actual media (photo, video, audio), but the metadata of the media.
After you, they fetched the assets you can either gather metadata about them to use or you can also edit the metadata or the assets.
So what data can you actually get after you have fetched the asset(s). Here is a quick list:
- mediaType – will return what type of asset it is, which can be either video or photo
- mediaSubtypes – will return the subtype of an asset, such as a panoramic photo or HDR photo
- sourceType – how the media entered the users Photo Library, such as TypeCloudShared, TypeiTunesSynced, TypeUserLibrary and TypeNone
- pixelWidth – the width in pixels
- pixelHeight – the height in pixels
- creationDate – the date and time when the asset was originally created
- modificationDate – the last date and time when the asset was modified
- location – the location where the asset was captured
- duration – the duration of the video asset
- favorite – a boolean value to indicate if this is favorite by the user or not
- hidden – a boolean value to indicate if this asset is hidden by the user or not
Here I am going to show how to fetch gallery data and fetch the image using Assert.
First Galley fetch.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
func fetchGallaryData(){ let status = PHPhotoLibrary.authorizationStatus() if (status == .denied || status == .restricted) { return }else{ PHPhotoLibrary.requestAuthorization { (authStatus) in if authStatus == .authorized{ let imageAsset = PHAsset.fetchAssets(with: .image, options: nil) if imageAsset.count>0{ self.imageAssets = imageAsset } } } |
Now Image fetches from Assert.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
func getUIImage(asset: PHAsset) -> UIImage? { var img: UIImage? let manager = PHImageManager.default() let options = PHImageRequestOptions() options.version = .original options.isSynchronous = true manager.requestImageData(for: asset, options: options) { data, _, _, _ in if let data = data { img = UIImage(data: data) } } return img } |
I hope it will help everyone.