PHImageManager throws exception while generating image - ios

I have this problem. When I try to generate image from asset using this method:
manager.requestImageForAsset(asset, targetSize: CGSize(width: asset.pixelWidth, height: asset.pixelHeight), contentMode: .AspectFit, options: option, resultHandler: {(result, info)->Void in
thumbnail = result!
As you can see I have put in the target size the width is "asset.pixelWidth" which I believe it returns the actual width of the asset, therefore I want the generated image to have the same dimensions as the original asset.
For some reason this throws an exception "unexpectedly found nil while unwrapping an Optional" on some images in my camera roll, Not all of them, but some of them. What is more interesting is that when I put the target size 100 for example for both width & height. It works on all assets on camera roll without exceptions.
Honestly I don't understand what the heck is happening here. So if can someone give me a clue that would be great.
This is the whole method used:
func getFullAssetImg(asset: PHAsset) -> UIImage {
let manager = PHImageManager.defaultManager()
let option = PHImageRequestOptions()
var thumbnail = UIImage()
option.synchronous = true
print(asset.pixelWidth)
print(asset.pixelHeight)
manager.requestImageForAsset(asset, targetSize: CGSize(width: asset.pixelWidth, height: asset.pixelHeight), contentMode: .AspectFit, options: option, resultHandler: {(result, info)->Void in
thumbnail = result!
})
return thumbnail
}
and this is how it's called:
let image = self.getFullAssetImg(asset)
--------UPDATE--------
When I added an option with value:
options.deliveryMode = .FastFormat
It worked! if I make this option with value HighQualityFormat it will throw exception
It's working now but if any one can tell me how this option solved my problem that could help other people.

Dears,
After spending one whole day i at last know whats happening here:
Thanks to this link: PHImageManager.requestImageForAsset returns nil
I noticed an option called networkAccessAllowed. This options makes the manager able to process an image on the cloud.
What was going wrong was that i was testing an image that was based on icloud so it was returning nil.
However this is the last piece of code I got to make things work:
func getFullAssetImg(asset: PHAsset) {
let manager2 = PHImageManager.defaultManager()
print(asset.pixelWidth)
print(asset.pixelHeight)
//let imageSize = CGSize(width: asset.pixelWidth, height: asset.pixelHeight)
let options = PHImageRequestOptions()
options.deliveryMode = .FastFormat
options.synchronous = true
options.networkAccessAllowed = true
manager2.requestImageForAsset(asset, targetSize: PHImageManagerMaximumSize, contentMode: .AspectFit, options: options, resultHandler: {(result, info)->Void in
if let thumbnail = result{
self.fullResolutionImages.addObject(thumbnail)
print("Full Resolution Image Added")
}
})
}
Hope it helps someone afterwards.
Thank you

Related

photo library access all photos cause PHImageManager to fetch image thumbnails

Below is how I fetch an image from the library. When I grant photo access to "Selected Photos" in the system settings for the app the image is as expected the largest size available. However, when I change photo access permissions to "All Photos" the code below produces a thumbnail of the original image. The app runs on ios 15. No iCloud is configured. Can anyone tell me please what is going on?
private func loadImage(assetId: String, done: #escaping (Image?) -> Void) {
let fetchResults: PHFetchResult<PHAsset> =
PHAsset.fetchAssets(withLocalIdentifiers: [assetId], options: nil)
guard let asset: PHAsset = fetchResults.firstObject else {
return
}
let manager = PHImageManager()
manager.requestImage(for: asset, targetSize: PHImageManagerMaximumSize,
contentMode: .aspectFit, options: nil) { (uiImage, _) in
if let uiImage = uiImage {
done(Image(uiImage: uiImage))
} else {
done(nil)
}
}
}
In general I can see why image quality depends on level of access. I was not able to find any documentation on this. What I did find though was that the deliveryMode of the request also matters. when I added the following options to the requestImage call the issue was solved.
let requestOptions = PHImageRequestOptions()
requestOptions.deliveryMode = .highQualityFormat
let manager = PHImageManager()
manager.requestImage(for: asset, targetSize: PHImageManagerMaximumSize,contentMode: .aspectFit, options: requestOptions) { (uiImage, _) in
//do something
}

iOS PHImageManager.default().requestImage callback is called twice for the same image

When I try to get an image with specific size, PHImageManager.default().requestImage is called twice with images of different sizes.
Here is the code:
static func load(from asset: PHAsset, targetSize: CGSize? = nil, completion: #escaping (UIImage?)->()) {
let options = PHImageRequestOptions()
options.isSynchronous = false
let id = UUID()
PHImageManager.default().requestImage(for: asset, targetSize: targetSize ?? PHImageManagerMaximumSize, contentMode: .aspectFill,
options: options, resultHandler: { image, _ in
print(id)
runInMain {
completion(image)
}
})
}
I added UUID to check if the same UUID is printed twice.
This is because the first callback returns a thumbnail while the full size image is being loaded.
From the official Apple documentation:
For an asynchronous request, Photos may call your result handler block more than once. Photos first calls the block to provide a low-quality image suitable for displaying temporarily while it prepares a high-quality image. (If low-quality image data is immediately available, the first call may occur before the method returns.) When the high-quality image is ready, Photos calls your result handler again to provide it. If the image manager has already cached the requested image at full quality, Photos calls your result handler only once. The PHImageResultIsDegradedKey key in the result handler’s info parameter indicates when Photos is providing a temporary low-quality image.
Swift 5 It calls only one time with a .deliveryMode = .highQualityFormat
let manager = PHImageManager.default()
var imageRequestOptions: PHImageRequestOptions {
let options = PHImageRequestOptions()
options.version = .current
options.resizeMode = .exact
options.deliveryMode = .highQualityFormat
options.isNetworkAccessAllowed = true
options.isSynchronous = true
return options
}
self.manager.requestImage(for: asset,targetSize: PHImageManagerMaximumSize, contentMode: .aspectFit, options: self.imageRequestOptions) { (thumbnail, info) in
if let img = thumbnail {
print(img)
}
}
Use:
requestOptions.deliveryMode = .highQualityFormat
instead of: requestOptions.deliveryMode = .opportunistic
.opportunistic - Photos automatically provides one or more results in order to balance image quality and responsiveness.

PHImageManager throws "First stage of an opportunistic image request returned a non-table format image, this is not fatal, but it is unexpected"

I am using PHImageCachingManager to get images for PHAsset. I need to use the opportunistic mode so that first the low resolution image available gets loaded and then as the full resolution becomes available, it gets loaded.
For some reason I keep getting the following warning and my low resolution image doesn't load. Image only loads when the highest resolution gets fetched (from iCloud).
The warning:
"First stage of an opportunistic image request returned a non-table format image, this is not fatal, but it is unexpected."
What am I doing wrong?
let imageRequestOptions = PHImageRequestOptions()
imageRequestOptions.isNetworkAccessAllowed = true
imageRequestOptions.deliveryMode = .opportunistic
let imageCachingManager = PHCachingImageManager()
imageCachingManager.requestImage(for: asset , targetSize: PHImageManagerMaximumSize, contentMode: .aspectFill, options: imageRequestOptions) { (image, infoDict) in
DispatchQueue.main.async {
if self.myImageView.identifierTag == asset.localIdentifier {
self.myImageView.image = image
}
}
}
imageCachingManager.requestImage(for: asset , targetSize: PHImageManagerMaximumSize, contentMode: .aspectFill, options: imageRequestOptions) { (image, infoDict) in
DispatchQueue.main.async {
if self.myImageView.identifierTag == asset.localIdentifier {
self.myImageView.image = image
}
}
}
You are setting the maximum size available as an image size. Change
targetSize: PHImageManagerMaximumSize
to
targetSize: CGSize(width: asset.pixelWidth, height: asset.pixelHeight)
or specify the image size like CGSize(with: 150, height: 150) unless you want to explode your device due to memory depletion.
PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
option.synchronous = YES;
``
将synchronous 属性设置为YES

Converting PHAsset to UIImage and displaying it to user

I'm using the BSImagePicker Image Picker controller (See here)
The image picker controller returns PHAsset rather than UIImage, so I found out how to convert PHAsset to UIImage using this function:
PHAsset to UIImage
func getAssetThumbnail(asset: PHAsset) -> UIImage {
let manager = PHImageManager.default()
let option = PHImageRequestOptions()
var thumbnail = UIImage()
option.isSynchronous = true
manager.requestImage(for: asset, targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFit, options: option, resultHandler: {(result, info)->Void in
thumbnail = result!
})
return thumbnail
}
Issue is that, I want to return the targetSize of PHImageManagerMaximumSize. Althought when this happens, I get an errorrThis application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread. This can lead to engine corruption and weird crashes.
The error doesn't occur when I set targetSize to CGSize(width: 100, height: 100)
Just you need to do to avoid your error is to force the application to modify the auto layout on the main thread. You can for example use a dispatcher in the main queue when you set your image.
For example:
let image = self.getAssetThumbnail(asset: <YourPHAsset>)
DispatchQueue.main.async {
self.imageView.image = image
}
The error should occur also when you use a targetSize... Strange...

PHImageManager requestImageForAsset returns nil sometimes for iCloud photos

Roughly 10% of the time PHImageManager.defaultManager().requestImageForAsset returns nil instead of a valid UIImage after first returning a valid though "degraded" UIImage. No error or other clue that I can see is returned in the info with the nil.
This seems to happen with photos that need to be downloaded from iCloud, with iCloud Photo Library and Optimize iPad Storage both enabled. I've tried changing the options, size, etc. but nothing seems to matter.
If I retry the requestImageForAsset after the failure it will usually correctly return a UIImage, though sometimes it requires a couple of retries.
Any idea what I might be doing wrong? Or is it just a bug in the Photos framework?
func photoImage(asset: PHAsset, size: CGSize, contentMode: UIViewContentMode, completionBlock:(image: UIImage, isPlaceholder: Bool) -> Void) -> PHImageRequestID? {
let options = PHImageRequestOptions()
options.networkAccessAllowed = true
options.version = .Current
options.deliveryMode = .Opportunistic
options.resizeMode = .Fast
let requestSize = !CGSizeEqualToSize(size, CGSizeZero) ? size : PHImageManagerMaximumSize
let requestContentMode = contentMode == .ScaleAspectFit ? PHImageContentMode.AspectFit : PHImageContentMode.AspectFill
return PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: requestSize, contentMode: requestContentMode, options: options)
{ (image: UIImage!, info: [NSObject : AnyObject]!) in
if let image = image {
let degraded = info[PHImageResultIsDegradedKey] as? Bool ?? false
completionBlock(image: photoBlock.rotatedImage(image), isPlaceholder: degraded)
} else {
let error = info[PHImageErrorKey] as? NSError
NSLog("Nil image error = \(error?.localizedDescription)")
}
}
}
I just went through this too.
By my tests the issue appears on devices that have the "Optimize Storage" option enabled and resides in the difference between the two methods bellow:
[[PHImageManager defaultManager] requestImageForAsset: ...]
This will successfully fetch remote iCloud images if your options are correctly configured.
[[PHImageManager defaultManager] requestImageDataForAsset:...]
This function only works for images that reside on the phones memory or that were recently fetched from iCloud by your app on any other one.
Here's a working snippet I'm using -bear with me the Obj-c :)
PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat; //I only want the highest possible quality
options.synchronous = NO;
options.networkAccessAllowed = YES;
options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
NSLog(#"%f", progress); //follow progress + update progress bar
};
[[PHImageManager defaultManager] requestImageForAsset:myPhAsset targetSize:self.view.frame.size contentMode:PHImageContentModeAspectFill options:options resultHandler:^(UIImage *image, NSDictionary *info) {
NSLog(#"reponse %#", info);
NSLog(#"got image %f %f", image.size.width, image.size.height);
}];
Full gist available on github
Updated for Swift 4:
let options = PHImageRequestOptions()
options.deliveryMode = PHImageRequestOptionsDeliveryMode.highQualityFormat
options.isSynchronous = false
options.isNetworkAccessAllowed = true
options.progressHandler = { (progress, error, stop, info) in
print("progress: \(progress)")
}
PHImageManager.default().requestImage(for: myPHAsset, targetSize: view.frame.size, contentMode: PHImageContentMode.aspectFill, options: options, resultHandler: {
(image, info) in
print("dict: \(String(describing: info))")
print("image size: \(String(describing: image?.size))")
})
I found that this had nothing to do with network or iCloud. It occasionally failed, even on images that were completely local. Sometimes it was images from my camera, sometimes it would be from images saved from the web.
I didn't find a fix, but a work around inspired by #Nadzeya that worked 100% of the time for me was to always request a target size equal to the asset size.
Eg.
PHCachingImageManager().requestImage(for: asset,
targetSize: CGSize(width: asset.pixelWidth, height: asset.pixelHeight) ,
contentMode: .aspectFit,
options: options,
resultHandler: { (image, info) in
if (image == nil) {
print("Error loading image")
print("\(info)")
} else {
view.image = image
}
});
I believe the drawbacks to this would be that we're getting the full image back in memory, and then forcing the ImageView to do the scaling, but at least in my use case, there wasn't a noticeable performance issue, and it was much better than loading a blurry or nil image.
A possible optimization here is to re-request the image at it's asset size only if the image comes back as nil.
Nothing of the above worked for me, but this solution did!
private func getUIImage(asset: PHAsset, retryAttempts: Int = 10) -> UIImage? {
var img: UIImage?
let manager = PHImageManager.default()
let options = PHImageRequestOptions()
options.version = .original
options.isSynchronous = true
options.isNetworkAccessAllowed = true
manager.requestImage(for: asset, targetSize: CGSize(width: asset.pixelWidth, height: asset.pixelHeight), contentMode: .aspectFit, options: options, resultHandler: { image, _ in
img = image
})
if img == nil && retryAttempts > 0 {
return getUIImage(asset: asset, retryAttempts: retryAttempts - 1)
}
return img
}
The difference here is the recursive retries. This works for me 100% of the times.
I 've tried many things
targetSize greater than (400, 400): not work
targetSize equals to asset size: not work
Disable Optimize Storage in iCloud Photos in Settings: not work
Dispatch requestImage to background queue: not work
Use PHImageManagerMaximumSize: not work
Use isNetworkAccessAllowed: not work
Play with different values in PHImageRequestOptions, like version, deliveryMode, resizeMode: not work
Add a progressHandler: not work
Call requestImage again it cases it failed: not work
All I get is nil UIImage and info with PHImageResultDeliveredImageFormatKey, like in this radar Photos Frameworks returns no error or image for particular assets
Use aspect fit
What work for me, see https://github.com/hyperoslo/Gallery/blob/master/Sources/Images/Image.swift#L34
Use targetSize with < 200: this is why I can load the thumbnail
Use aspectFit: Specify to contentMode does the trick for me
Here is the code
let options = PHImageRequestOptions()
options.isSynchronous = true
options.isNetworkAccessAllowed = true
var result: UIImage? = nil
PHImageManager.default().requestImage(
for: asset,
targetSize: size,
contentMode: .aspectFit,
options: options) { (image, _) in
result = image
}
return result
Fetch asynchronously
The above may cause race condition, so make sure you fetch asynchronously, which means no isSynchronous. Take a look at https://github.com/hyperoslo/Gallery/pull/72
I was seeing this as well, and the only thing that worked for me was setting options.isSynchronous = false. My particular options are:
options.isNetworkAccessAllowed = true
options.deliveryMode = .highQualityFormat
options.version = .current
options.resizeMode = .exact
options.isSynchronous = false
Try to use targetSize greater than (400, 400).
It helped me.
What it worked for me was letting PHImageManager loading the asset data synchronously, but from an asynchronous background thread. Simplified it looks like this:
DispatchQueue.global(qos: .userInitiated).async {
let requestOptions = PHImageRequestOptions()
requestOptions.isNetworkAccessAllowed = true
requestOptions.version = .current
requestOptions.deliveryMode = .opportunistic
requestOptions.isSynchronous = true
PHImageManager.default().requestImage(for: asset, targetSize: size, contentMode: .aspectFit, options: requestOptions) { image, _ in
DispatchQueue.main.async { /* do something with the image */ }
}
}
Starting with iOS 14, this could also happen if the user has not granted permission to use that particular photo using the limited photos picker. For more information, https://developer.apple.com/documentation/photokit/delivering_a_great_privacy_experience_in_your_photos_app
The following fixed my issue:
let options = PHImageRequestOptions()
options.isSynchronous = false
options.isNetworkAccessAllowed = true
options.deliveryMode = .opportunistic
options.version = .current
options.resizeMode = .exact
I was also getting nil for iCloud images. It didn't make a difference if I used requestImage or requestImageData flavor of the method. My problem, it turns out, was that my device was connected to the network via Charles Proxy since I wanted to monitor requests and responses app made. For some reason device couldn't work with iCloud if connected this way. Once I turned off the proxy app could get iCloud images.
The solution for me was setting a targetSize
var image: UIImage?
let options = PHImageRequestOptions()
options.isNetworkAccessAllowed = true
options.isSynchronous = true
options.resizeMode = PHImageRequestOptionsResizeMode.exact
let targetSize = CGSize(width:1200, height:1200)
PHImageManager.default().requestImage(for: self, targetSize: targetSize, contentMode: PHImageContentMode.aspectFit, options: options) { (receivedImage, info) in
if let formAnImage = receivedImage
{
image = formAnImage
}
}
Good coding!

Resources