1

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!

random_0620
  • 1,636
  • 5
  • 23
  • 44

2 Answers2

1

Taking @James Zaghini answer to the another level.

You also need to check UIImage or info is nil or not.

guard let asset = asset else { return }

let imageManager = PHCachingImageManager();
imageManager.requestImage(for: asset, targetSize: CGSize(width:100,height:100), contentMode: .aspectFit, options: options, resultHandler: {(image,info) -> Void in
    if let img = image{
        print("Got Image")
    }
    if let imgInfo = info{
        print("Info")
    }
})
Sohil R. Memon
  • 9,404
  • 1
  • 31
  • 57
0

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.

random_0620
  • 1,636
  • 5
  • 23
  • 44