Search code examples
iosswiftphotokit

App crashes when I call requestImage


My app crashes with error Thread 1: EXC_BAD_INSTRUCTION when this method is called:

imageManager.requestImage(for: asset!, targetSize: CGSize(width:100,height:100), contentMode: .aspectFit, options: options, resultHandler: {(image,info) -> Void in})

Full code in view did load:

    override func viewDidLoad() {
    super.viewDidLoad()
    collectionView.delegate = self;
    collectionView.dataSource = self;

    let fetchResult = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: nil);
    let asset = fetchResult.firstObject;

    let options = PHImageRequestOptions()
    options.deliveryMode = .fastFormat
    options.isSynchronous = true

    let imageManager = PHCachingImageManager();
    imageManager.requestImage(for: asset!, targetSize: CGSize(width:100,height:100), contentMode: .aspectFit, options: options, resultHandler: {(image,info) -> Void in
    print("Got image")
    })
}

Anyone know what might be causing the error? I think it has something to do with the closure but I'm not sure what is wrong...

here is the method syntax which I am trying to call:

func requestImage(for asset: PHAsset, targetSize: CGSize, contentMode: PHImageContentMode, options: PHImageRequestOptions?, resultHandler: (UIImage?, [NSObject : AnyObject]?) -> Void) -> PHImageRequestID

Thanks!


Solution

  • Okay the answer has nothing to do with the line of code. I had to go to View then Debug then click view console so I could see the console print the error message telling me to add the key NSPhotoLibraryUsageDescription into the Info.plist.

    When you are using the photos framework you have to include the key with a reason for wanting to access the camera roll. Once I added this key into the plist everything worked.