我最近改变了我的collectionView,以便它在CollectionViewController中,而不是在ViewController中的视图中。 当我尝试保存照片或从库中选择照片以显示在collectionView中并保存到相册中时(如果拍照)它会崩溃:
最新[9553:146224] [通用]创建具有未知类型的图像格式是错误
致命错误:在解包可选值时意外发现nil
它在我的其他项目中工作正常,这是视图控制器中的集合视图。
问题肯定在UIImagePickerControllerDelegate方法中,但我无法解决问题。
以下是项目失败的代码
import UIKit
import Photos
class GalleryViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var imageArray = [UIImage]()
var assetCollection: PHAssetCollection = PHAssetCollection()
let albumName = "Test"
var albumFound : Bool = false
var photosAsset: PHFetchResult<PHAsset>!
let reuseIdentifier = "PhotoCell"
@IBAction func btnPhotoAlbum(_ sender: Any) {
let picker : UIImagePickerController = UIImagePickerController()
picker.sourceType = UIImagePickerControllerSourceType.photoLibrary
picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
picker.delegate = self
picker.allowsEditing = false
self.present(picker, animated: true, completion: nil)
}
@IBAction func btnCamera(_ sender: AnyObject) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){
//load the camera interface
let picker : UIImagePickerController = UIImagePickerController()
picker.sourceType = UIImagePickerControllerSourceType.camera
picker.delegate = self
picker.allowsEditing = false
self.present(picker, animated: true, completion: nil)
}else{
//no camera available
let alert = UIAlertController(title: "Error", message: "There is no camera available", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: {(alertAction)in
alert.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
}
override func viewDidLoad() {
super.viewDidLoad()
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", albumName)
let collection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
if let _:AnyObject = collection.firstObject{
//found the album
self.albumFound = true
self.assetCollection = collection.firstObject! as PHAssetCollection
}else{
var albumPlaceholder:PHObjectPlaceholder!
//create the folder
NSLog("\nFolder \"%@\" does not exist\nCreating now...", albumName)
PHPhotoLibrary.shared().performChanges({
let request = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: self.albumName)
albumPlaceholder = request.placeholderForCreatedAssetCollection
},
completionHandler: {(success, error)in
if(success){
print("Successfully created folder")
self.albumFound = true
let collection = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [albumPlaceholder.localIdentifier], options: nil)
self.assetCollection = collection.firstObject! as PHAssetCollection
}else{
print("Error creating folder")
self.albumFound = false
}
})
}
}
override func viewWillAppear(_ animated: Bool) {
self.imageArray.removeAll()
grabPhotos()
}
func grabPhotos(){
let imgManager = PHImageManager.default()
let requestOptions = PHImageRequestOptions()
requestOptions.isSynchronous = true
requestOptions.deliveryMode = .highQualityFormat
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
if let fetchResult : PHFetchResult = PHAsset.fetchAssets(in: self.assetCollection, options: fetchOptions) {
if fetchResult.count > 0 {
for i in 0..<fetchResult.count{
imgManager.requestImage(for: fetchResult.object(at: i) as PHAsset, targetSize: CGSize(width:200, height: 200), contentMode: .aspectFill, options: requestOptions, resultHandler: {
image, error in
self.imageArray.append(image!)
})
}
self.collectionView!.reloadData()
}
else{
print("you got no photos!")
}
}
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imageArray.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
let imageView = cell.viewWithTag(1) as! UIImageView
imageView.image = imageArray[indexPath.row]
return cell
}
//UIImagePickerControllerDelegate Methods
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]){
if let image: UIImage = info[UIImagePickerControllerOriginalImage] as? UIImage{
PHPhotoLibrary.shared().performChanges({
let createAssetRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
let assetPlaceholder = createAssetRequest.placeholderForCreatedAsset
if let albumChangeRequest = PHAssetCollectionChangeRequest(for: self.assetCollection, assets: self.photosAsset) {
let fastEnumeration = NSArray(array: [assetPlaceholder!] as [PHObjectPlaceholder])
albumChangeRequest.addAssets(fastEnumeration) }
}, completionHandler: {(success, error)in
NSLog("Adding Image to Library -> %@", (success ? "Sucess":"Error!"))
picker.dismiss(animated: true, completion: nil)
})
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController){
picker.dismiss(animated: true, completion: nil)
}
}