码迷,mamicode.com
首页 > 编程语言 > 详细

swift 将图片保存到自定义相册中

时间:2016-11-01 14:00:33      阅读:587      评论:0      收藏:0      [点我收藏+]

标签:log   request   mat   share   ges   hresult   create   style   uikit   

import UIKit
import Photos
@available(iOS 8.0, *)
class CustomAblum: NSObject {
    static let sharedInstance = CustomAblum()
    
    var assetCollection: PHAssetCollection!
    var albumFound : Bool = false
    var photosAsset: PHFetchResult!
    var collection: PHAssetCollection!
    var assetCollectionPlaceholder: PHObjectPlaceholder!
    static let albumName = "扫描图片"
    override init() {
        super.init();
        self.createAlbum()
    }
    private func createAlbum() {
        let fetchOptions = PHFetchOptions()
        fetchOptions.predicate = NSPredicate(format: "title = %@",CustomAblum.albumName);
        let collection : PHFetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions)
        
        if let _: AnyObject = collection.firstObject {
            self.albumFound = true
            assetCollection = collection.firstObject as! PHAssetCollection
        } else {
            PHPhotoLibrary.sharedPhotoLibrary().performChanges({
                let createAlbumRequest : PHAssetCollectionChangeRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(CustomAblum.albumName);
                self.assetCollectionPlaceholder = createAlbumRequest.placeholderForCreatedAssetCollection
                }, completionHandler: { success, error in
                    self.albumFound = (success ? true: false)
                    
                    if (success) {
                        let collectionFetchResult = PHAssetCollection.fetchAssetCollectionsWithLocalIdentifiers([self.assetCollectionPlaceholder.localIdentifier], options: nil)
                        print(collectionFetchResult)
                        self.assetCollection = collectionFetchResult.firstObject as! PHAssetCollection
                    }
            })
        }
    }
    func saveImage(image: UIImage) {
        if self.assetCollection != nil {
            PHPhotoLibrary.sharedPhotoLibrary().performChanges({
                let assetChangeRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(image)
                let assetPlaceholder = assetChangeRequest.placeholderForCreatedAsset
                let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: self.assetCollection)
                albumChangeRequest?.addAssets([assetPlaceholder!])
                }, completionHandler: nil)
        }
    }
    
}

使用时直接掉saveImage方法。

swift 将图片保存到自定义相册中

标签:log   request   mat   share   ges   hresult   create   style   uikit   

原文地址:http://www.cnblogs.com/sunmair/p/6018946.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!