Photos storage, access, change photos

Photos storage, access, change photos
images from the network

Preface:

Photo album to save the system album, there are usually three ways:

  • UIImageWriteToSavedPhotosAlbum () method preservation
  • Is to use the Photos framework to achieve.
  • ALAssetsLibrary is marked as obsolete after iOS9.0, apple recommends using the Photos framework instead
Q: UIImageWriteToSavedPhotosAlbum () save the picture is very simple, but why use Photos?

Answer:
1, Photos can be identified as the photo album, easy to save out after their
2, Photos synchronous operation, can also save multiple pictures,
3 can be stored in a particular album
— (there are other advantages, friends can comment on the
Photos framework Bozhuan) function is very powerful, more than save function

The following detailed explanation of this new framework Photos iOS8.0:
on the basic composition of the PhotoKit: (this article takes the latest version of the swift, OC had to slowly transition to the swift)

A PHAsset: represents resource in photo gallery, similar to ALAsset, the PHAsset parameters can be obtained and preserved
PHFetchOptions: resources access to resources, can pass the nil, using the default
PHAssetCollection: PHCollection subclasses, said an album or a moment, or a “smart album (system given a series of albums, for example: the recent video collection list, delete, etc., as shown in the figure below)
PHFetchResult: said a series of resources in the result set, can also be the album set,
PHImageManager from the PHCollection method for processing resource loading, loading pictures with caching can pass a PHImageRequestOptions control resources The output size specifications of
PHImageRequestOptions: as mentioned above, a series of parameters of
PHPhotoLibrary control: when loading the image represented by a set of resource management and collection of photo applications, including stored in the local device and (permission) resources stored in the iCloud in the photo. You can use this object to perform change of objects in the photo library set for example, editing metadata or content, insert new resources or re arrangement of a member of the collection, you can also register the photos in the content or metadata collection and message changes using the photo library object, and verify whether the user has authorized you the application of access photo content (the description of the PHPhotoLibrary at the end of the article)

First, save photos

1, UIImageWriteToSavedPhotosAlbum () save photos
Let image = self.imageView.image! UIImageWriteToSavedPhotosAlbum (image, nil, nil, Nil)
2, Photos save photos

Save photos to photo album

Func savePhoto (image: UIImage) {PHPhotoLibrary.shared (.PerformChanges) creating an asset ({/ / Request from the image. let creationRequest = PHAssetChangeRequest.creationRequestForAsset (from: image) let assetPlaceholder = creationRequest.placeholderForCreatedAsset self.localId = assetPlaceholder / save symbol?.localIdentifier} completionHandler: {success, error in if! Success creating asset: {print ("error / (error) else {print}") ("success") / / by identifier to obtain the corresponding resource let assetResult = PHAsset.fetchAssets (withLocalIdentifiers: [self.localId], optio Ns: nil let asset let) = assetResult[0] options = PHContentEditingInputRequestOptions (options.canHandleAdjustmentData) = {(adjustmeta: PHAdjustmentData) -> Bool in return true;} / / get the image path saved asset.requestContentEditingInput (with: options, completionHandler: (contentEditingInput:PHContentEditingInput, info: {? [AnyHashable: Any] print (in) address: "contentEditingInput!.fullSizeImageURL!}))}})}

Save photos to a specific album

Func savePhoto (image: UIImage, album: PHAssetCollection) {PHPhotoLibrary.shared (.PerformChanges) creating an asset ({/ / Request from the image. let creationRequest = PHAssetChangeRequest.creationRequestForAsset (from: image) editing the album. guard / / Request / / let addAssetRequest = PHAssetCollectionChangeRequest (for: album else) {return} let assetPlaceholder = creationRequest.placeholderForCreatedAsset / self.localId = assetPlaceholder save symbol.LocalIdentifier? Get a placeholder for the new / asset and add it to the album editing request. addAssetRequest.addAssets ([creationRequest.placeholderForCreat EdAsset! As NSArray)}, {completionHandler: success, error in if! Success {print ("error creating / asset: (error)} {print (" else ") added to the custom album success")}})}

Two, create custom album

Func createAssetCollection (->); Void{(PHPhotoLibrary.shared).PerformChanges ({PHAssetCollectionChangeRequest.creationRequestForAssetCollection (withTitle: "I am Wade") {}) (isSuccess: Bool error) in if! IsSuccess {print ("error creating assetCollection: (error) / else (" {print ")}} success") //use the PHObjectPlaceholder object provided by the change request. After the change block completes, use the placeholder object localIdentifier property to fetch the s created object.}}

Note: can use PHObjectPlaceholder for the album to sit logo, and then after the completion of the change (change block completes), to get the album just created

Three, Get Album

Get in the can be acquired from the PHAssetCollection album can also be a resource, but no matter what kind of content, the unified package PHFetchResult object, so although PHAssetCollection acquired results may be varied, but through the PHFetchResult method can be used to deal with the unified content (i.e. PHFetchResult traversal)

1, the list of all albums smart album

Func getAlbum (let) {smartAlbums: PHFetchResult = PHAssetCollection.fetchAssetCollections (with: PHAssetCollectionType.smartAlbum, subtype: PHAssetCollectionSubtype.albumRegular, options: nil (print) "intelligence / (smartAlbums.count)") / / then stored in smartAlbums should be each corresponding to the PHAssetCollection for index smart album in 0..< smartAlbums.count {/ / get a photo album (PHAssetCollection) let collection = smartAlbums[index] if collection.isKind (of:) PHAssetCollection.classForCoder (assetCollection = let) {/ / collection / / assignment from every intelligent access to the album contained in PHFetchResult is the real resources (PHAss Et = PHAsset.fetchAssets (in:) let assetsFetchResults:PHFetchResult assetCollection, options: nil (print) / (assetCollection.localizedTitle) album, there are pictures of the number: / (assetsFetchResults.count) "(assetsFetchResults.enumerateObjects) (asset, I, nil {/ / in) to get each resource (PHAsset) (" print / (asset)} "))}}}

2, lists the user created albums, and get each album in the PHAsset object

Func (fetchAllUserCreatedAlbum) {/ / get custom album Let topLevelUserCollections:PHFetchResult = PHCollectionList.fetchTopLevelUserCollections (with: nil //topLevelUserCollections) is stored in the corresponding album each user created PHAssetCollection print ("user created / (topLevelUserCollections.count) for I in 0..<"); topLevelUserCollections.count {/ / get a photo of let collection if collection.isKind (of: PHAssetCollection.classForCoder = topLevelUserCollections[i] (let)) {/ / collection / / assetCollection = assignment from every smart album get included in the PHFetchResult is the real resources (PHAsse T = PHAsset.fetchAssets (in:) let assetsFetchResults:PHFetchResult assetCollection as PHAssetCollection, options: nil! (print) / (assetCollection.localizedTitle) album, there are pictures of the number: / (assetsFetchResults.count) ") / / traverse custom photo album, photo album if assetCollection.localizedTitle stored in a custom" HiWade "= = {self.savePhoto (image: self.imageView.image, album: assetCollection! As! PHAssetCollection (assetsFetchResults.enumerateObjects)} {(asset, I, nil print (in) / (asset)")}})} print ("all set of resources, according to the time sequence: (self /.GetAllSourceCo (llection) ")) / / get momentAlbum let momentAlbum:PHFetchResult = PHAssetCollection.fetchAssetCollections (with:.Moment, subtype:.AlbumRegular, options: nil (print) momentAlbum:/ (momentAlbum.count) for I in 0..<"); momentAlbum.count collection if collection.isKind {let = momentAlbum[i] (of:) PHAssetCollection.classForCoder (assetCollection = let) {/ / collection / / assignment from every intelligent access to the album contained in PHFetchResult is the real resource (PHAsset) let assetsFetchResults:PHFetchResult = PHAsset.fetchAssets (in: assetCollection, options: nil (print) / (assetCollection.localizedTitle). There are photos, number: / (assetsFetchResults.count) "(assetsFetchResults.enumerateObjects) (asset, I, nil {print (in)" / "(asset)) {assert})}else (false, error)}}}

3, get a collection of all resources, and by the time the resource creation

Func getAllSourceCollection (->); Array< PHAsset> options:PHFetchOptions) {let = PHFetchOptions.init (VaR assetArr = [PHAsset] (options.sortDescriptors) = [NSSortDescriptor.init (key: creationDate, ascending: true)] let assetFetchResults:PHFetchResult = PHAsset.fetchAssets (with: options) for I in 0..< assetFetchResults.count {/ / obtain a resource (PHAsset) let = assetFetchResults[i] / asset self.getAssetOrigin (asset: asset) self.getAssetThumbnail (asset: assetFetchResults[assetFetchResults.count-1]) / / add to the array of assetArr.append (asset) return assetArr}}

4, get thumbnail method

Func getAssetThumbnail (asset:PHAsset) -> Void let Manager = {/ / get thumbnail PHImageManager.default (let) = PHImageRequestOptions (option) / / you can set the image quality, and also have version control parameters of image clipping / return a single result, will block the thread before returning, the default is false = true (for: asset manager.requestImage option.isSynchronous targetSize:, CGSize.init (width: 100, height: 200), contentMode:.AspectFit, options: option) {(thumbnailImage, info) in print ("thumbnails: / (thumbnailImage), image information: / (info)") self.imageView.image = thumbnailImage;}}

5, access to the original method

Func getAssetOrigin (asset:PHAsset) -> Void let Manager = {/ / get the original PHImageManager.default (let) = PHImageRequestOptions (option) / / you can set the image quality, and also have version control parameters of image clipping option.isSynchronous = true (for: asset, manager.requestImage targetSize:PHImageManagerMaximumSize, contentMode:.AspectFit, options: option) {(originImage, info) in self.imageView.image = originImage; print ("Original: / (originImage), image information: / (info)")}}

PHPhotoLibrary extension:

Class func authorizationStatus ()

Return whether you can enter the album’s license information
Returns your app s authorization accessing the user ‘s Photos for library. about information

Add NSPhotoLibraryUsageDescription key to Info.plist

If the user is not allowed, it will return not Determined, which can be called request Authorization (_: I)

Class func requestAuthorization ((PHAuthorizationStatus) -> Void)

Ask the user for access to the photo library.

Class func shared ()

Get shared photo library object.

Func performChanges ((completionHandler:) -> Void ((Bool, Error?) -> Void = = Nil)

Asynchronous Photo Library

Func performChangesAndWait (() -> Void)

Synchronize Photo Library

Func register (PHPhotoLibraryChangeObserver)

Register an object to monitor whether the photo library changed
Registers an to receive when objects in the photo library change. messages object

Func unregisterChangeObserver (PHPhotoLibraryChangeObserver)

Remove registration, no longer receive change message
Unregisters object that it no longer receives change an so messages.

This part of the reference API Reference
code link