0
這聽起來可能是重複的,但在搜索之後,我仍然沒有得到Swift 3的預期答案。 在我嘗試添加資產時使用addAssets()
創建資產佔位符方法Xcode建議我將cast assetPlacehoder轉換爲FastEnumeration類型。當我這樣做的時候,它會導致一個異常。有人可以幫我嗎?如何在Swift 3中創建自定義相冊iOS 10
這聽起來可能是重複的,但在搜索之後,我仍然沒有得到Swift 3的預期答案。 在我嘗試添加資產時使用addAssets()
創建資產佔位符方法Xcode建議我將cast assetPlacehoder轉換爲FastEnumeration類型。當我這樣做的時候,它會導致一個異常。有人可以幫我嗎?如何在Swift 3中創建自定義相冊iOS 10
使用此課程並在需要時和在將圖像添加到相冊之前徵求權限。
class CustomPhotoAlbum: NSObject {
static let albumName = "YourAlbumName"
static let sharedInstance = CustomPhotoAlbum()
var assetCollection: PHAssetCollection!
override init() {
super.init()
if let assetCollection = fetchAssetCollectionForAlbum() {
self.assetCollection = assetCollection
return
}
}
func requestAuthorizationHandler(status: PHAuthorizationStatus) {
if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.authorized {
// ideally this ensures the creation of the photo album even if authorization wasn't prompted till after init was done
print("trying again to create the album")
self.createAlbum()
} else {
print("should really prompt the user to let them know it's failed")
}
}
func createAlbum() {
PHPhotoLibrary.shared().performChanges({
PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: CustomPhotoAlbum.albumName) // create an asset collection with the album name
}) { success, error in
if success {
self.assetCollection = self.fetchAssetCollectionForAlbum()
} else {
print("error \(String(describing: error))")
}
}
}
func fetchAssetCollectionForAlbum() -> PHAssetCollection? {
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", CustomPhotoAlbum.albumName)
let collection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
if let _: AnyObject = collection.firstObject {
return collection.firstObject
}
return nil
}
func save(image: UIImage , completion : @escaping() ->()) {
if assetCollection == nil {
return // if there was an error upstream, skip the save
}
PHPhotoLibrary.shared().performChanges({
let assetChangeRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
let assetPlaceHolder = assetChangeRequest.placeholderForCreatedAsset
let albumChangeRequest = PHAssetCollectionChangeRequest(for: self.assetCollection)
let enumeration: NSArray = [assetPlaceHolder!]
if self.assetCollection.estimatedAssetCount == 0
{
albumChangeRequest!.addAssets(enumeration)
}
else {
albumChangeRequest!.insertAssets(enumeration, at: [0])
}
}, completionHandler: { status , errror in
completion()
})
}
}
調用此方法要保存圖像。
CustomPhotoAlbum.sharedInstance.save(image: YourImage, completion: {
DispatchQueue.main.async(execute: {
//"Any UI update should be in main thread."
})
})
什麼曾經調用requestAuthorizationHandler?應該首先調用它來創建相冊。 – VagueExplanation
您可以發佈您收到的例外嗎? – bjtitus
@ bjtitus,這是我得到的異常:'[通用]創建一個未知類型的圖像格式是一個錯誤 無法將類型'PHAsset'(0x15e4a0578)的值轉換爲'NSFastEnumeration'(0x15d4d86e0).' –