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...
Related
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.
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
I have an array of image assets. I have to turn those assets into images, add them to an array and upload them to Firebase Database. I have 2 issues with this.
Issue 1:
In a custom UICollectionViewCell I display all the images that the user has selected, I see 4 images in the cell, when I've selected 4 images from the Photos (I'm using a custom framework). Now, when I call requestImage method, I get double the amount of images in the array that's supposed to convert each asset from the asset array and store it into a UIImage array called assetsTurnedIntoImages. I read more about it and it's related to the PHImageRequestOptions and if its isSynchronous property returns true or false, that or if PHImageRequestOptions is nil. Now, obviously I didn't get something because my code still doesn't work.
Issue 2:
As you can see from the code below, the targetSize gives me a somewhat thumbnail image size. When I upload the image to the storage, I don't need a thumbnail, I need it's original size. If I set it to PHImageManagerMaximumSize I get an error:
"Connection to assetsd was interrupted or assetsd died”
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoPostCVCell", for: indexPath) as! PhotoPostCVCell
if let takenImage = cameraPhotoUIImage
{
cell.cellImage.image = takenImage
}
if assets.count > 0
{
let asset = assets[indexPath.row]
let requestOptions = PHImageRequestOptions()
requestOptions.isSynchronous = true // synchronous works better when grabbing all images
requestOptions.deliveryMode = .opportunistic
imageManager.requestImage(for: asset, targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFill, options: requestOptions)
{ (image, _) in
DispatchQueue.main.async {
print("WE ARE IN")
cell.cellImage.image = image!
self.assetsTurnedIntoImages.append(image!)
}
}
}
return cell
}
Change the option could solve the problem:
options.deliveryMode = .highQualityFormat
I found that solution in the source code:
#available(iOS 8, iOS 8, *)
public enum PHImageRequestOptionsDeliveryMode : Int {
#available(iOS 8, *)
case opportunistic = 0 // client may get several image results when the call is asynchronous or will get one result when the call is synchronous
#available(iOS 8, *)
case highQualityFormat = 1 // client will get one result only and it will be as asked or better than asked
#available(iOS 8, *)
case fastFormat = 2 // client will get one result only and it may be degraded
}
To avoid completion handler's twice calling, just add an option in this request to make it synchronous
let options = PHImageRequestOptions()
options.isSynchronous = true
let asset: PHAsset = self.photoAsset?[indexPath.item] as! PHAsset
PHImageManager.default().requestImage(for: asset, targetSize: CGSize(width: 1200, height: 1200), contentMode: .aspectFit, options: options, resultHandler: {(result, info) in
if result != nil {
//do your work here
}
})
To avoid crash on loading image you should compress the image or reduce its size for further work
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
So I am using the SwipeView library (https://github.com/nicklockwood/SwipeView) to show images using the Photos framework for iOS8.
However, when I call the requestImageForAsset I notice I am getting two results, a thumbnail size, and the bigger size that I want. However, the bigger image isn't loaded (it's called async I understand) in time to return, so it returns the small image.
This code might make more sense.
func swipeView(swipeView: SwipeView!, viewForItemAtIndex index: Int, reusingView view: UIView!) -> UIView! {
let asset: PHAsset = self.photosAsset[index] as PHAsset
var imageView: UIImageView!
let screenSize: CGSize = UIScreen.mainScreen().bounds.size
let targetSize = CGSizeMake(screenSize.width, screenSize.height)
var options = PHImageRequestOptions()
// options.deliveryMode = PHImageRequestOptionsDeliveryMode.Opportunistic
options.resizeMode = PHImageRequestOptionsResizeMode.Exact
PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: targetSize, contentMode: .AspectFill, options: options, resultHandler: {(result, info)in
println("huhuhuh")
println(result.size)
println(info)
imageView = UIImageView(image: result)
})
println("setting view)
return imageView
}
Here is the log output:
Enteredhuhuhuh
(33.5,60.0)
SETTING VIEW
huhuhuh
(320.0,568.0)
As you can see it returns the image view before the big image is recieved. How do I make it return this larger image so it's not showing the thumbnai?
Thanks.
Read header of PHImageManager class
If -[PHImageRequestOptions isSynchronous] returns NO (or options is
nil), resultHandler may be called 1 or more times. Typically in this
case, resultHandler will be called asynchronously on the main thread
with the requested results. However, if deliveryMode =
PHImageRequestOptionsDeliveryModeOpportunistic, resultHandler may be
called synchronously on the calling thread if any image data is
immediately available. If the image data returned in this first pass
is of insufficient quality, resultHandler will be called again,
asychronously on the main thread at a later time with the "correct"
results. If the request is cancelled, resultHandler may not be called
at all. If -[PHImageRequestOptions isSynchronous] returns YES,
resultHandler will be called exactly once, synchronously and on the
calling thread. Synchronous requests cannot be cancelled.
resultHandler for asynchronous requests, always called on main thread
So, what you want to do is that you make resultHandler to be called synchronously
PHImageRequestOptions *option = [PHImageRequestOptions new];
option.synchronous = YES;
[[PHImageManager defaultManager] requestImageForAsset:asset targetSize:target contentMode:PHImageContentModeAspectFill options:option resultHandler:^(UIImage *result, NSDictionary *info) {
//this block will be called synchronously
}];
So your block will be called before ending your method
Good luck!
By default the requestImageForAsset works as asynchronous. So in your method the return statement will be executed even before the image is retrieved. So my suggestion is instead of returning the imageView, pass the imageView in that you need to populate the image:
func swipeView(swipeView: SwipeView!, viewForItemAtIndex index: Int, reusingView view: UIView!, yourImageView: UIImageView)
{
let asset: PHAsset = self.photosAsset[index] as PHAsset
var imageView: UIImageView! = yourImageView;
let screenSize: CGSize = UIScreen.mainScreen().bounds.size
let targetSize = CGSizeMake(screenSize.width, screenSize.height)
var options = PHImageRequestOptions()
options.resizeMode = PHImageRequestOptionsResizeMode.Exact
PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: targetSize, contentMode: .AspectFill, options: options, resultHandler: {(result, info)in
imageView.image = result;
})
}
Note:
Another option is you can fire a notification with the result image from the resultHandler. But I prefer the above mentioned method.
Refer PHImageManager for more information.
resultHandler: block has info dictionary which may contain Boolean value for PHImageResultIsDegradedKey key, which indicates whether the result image is a low-quality substitute for the requested image.
Here's what documentation says:
PHImageResultIsDegradedKey: A Boolean value indicating whether the
result image is a low-quality substitute for the requested image.
(NSNumber)
If YES, the result parameter of your resultHandler block contains a
low-quality image because Photos could not yet provide a
higher-quality image. Depending on your settings in the
PHImageRequestOptions object that you provided with the request,
Photos may call your result handler block again to provide a
higher-quality image.
You shouldn't rewrite imageView inside block, just set image to it and everything should work as you expect. To avoid showing two images you can check the size of image before assigning.
var imageView = UIImageView()
...
...
PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: targetSize, contentMode: .AspectFill, options: options, resultHandler: {(result, info)in
println("huhuhuh")
println(result.size)
println(info)
if result.size.width > 1000 && result.size.height > 1000 { // add any size you want
imageView.setImage(result)
}
})
Check the Apple Documentation for this method here. In that they are saying:
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.)
It might be taking time, in your case for fetching original size image. Otherwise your code seems okay to me.
try this will work for asynchronously too.
[[PHImageManager defaultManager] requestImageForAsset:asset targetSize:target contentMode:PHImageContentModeAspectFill options:option resultHandler:^(UIImage *result, NSDictionary *info) {
if ([info objectForKey:#"PHImageFileURLKey"]) {
//your code
}
}];
Use below options, swift 3.0
publi var imageRequestOptions: PHImageRequestOptions{
let options = PHImageRequestOptions()
options.version = .current
options.resizeMode = .exact
options.deliveryMode = .highQualityFormat
options.isNetworkAccessAllowed = true
options.isSynchronous = true
return options}
here is the best solution I had applied and it's working perfectly
let imageManager = PHImageManager.default()
let requestOptions = PHImageRequestOptions()
requestOptions.deliveryMode = .highQualityFormat
requestOptions.version = .current
requestOptions.resizeMode = .exact
requestOptions.isSynchronous = true
imageManager.requestImage(for: self.assets.first!, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFit, options: nil, resultHandler: { image, info in
if let info = info, info["PHImageFileUTIKey"] == nil {
if let isDegraded = info[PHImageResultIsDegradedKey] as? Bool, isDegraded {
//Here is Low quality image , in this case return
print("PHImageResultIsDegradedKey =======> \(isDegraded)")
return
}
//Here you got high resilutions image
}
})