0

I ran into a problem when trying to pick photo from gallery (app crashes when I pick image uploaded on iCloud). So my first solution was to check if image is on device and if not, then download it from iCloud.

I used this code

let manager = PHImageManager.default()
let requestOptions = PHImageRequestOptions()
requestOptions.resizeMode = .exact
requestOptions.deliveryMode = .highQualityFormat;

// Request Image
manager.requestImageData(for: asset, options: requestOptions, resultHandler: { (data, str, orientation, info) -> Void in
// Do somethign with Image Data
})

I get imageData in this situation, but if I want to save it, it saves into new photo. So I get copy of image in Photos instead getting one original image that stores on device.

So my question is how to download image without re-saving it. Basically I want same behaviour as in photos app (when photo is not on device, it downloads photo and save it into same picture instead creating copy of it)

Richard
  • 97
  • 8

1 Answers1

1

I faced this issue, here is a workaround for it:

Set isNetworkAccessAllowed to false:

requestOptions.isNetworkAccessAllowed = false

That's because you need to make sure that we will not fetch it from the iCloud. At this point, if the image is not downloaded, the data in resultHandler should be nil:

manager.requestImageData(for: PHAsset(), options: requestOptions, resultHandler: { (data, str, orientation, info) -> Void in
    if let fetchedData = data {
        // the image is already downloaded
    } else {
        // the image is not downloaded...
        // now what you should do is to set isNetworkAccessAllowed to true
        // and make a new request to get it from iCloud.
    }
})

Furthermore, you could leverage PHImageResultIsInCloudKey:

manager.requestImageData(for: PHAsset(), options: requestOptions, resultHandler: { (data, str, orientation, info) -> Void in
    if let keyNSNumber = info?[PHImageResultIsInCloudKey] as? NSNumber {
        if keyNSNumber.boolValue {
            // its on iCloud...
            // read the "keep in mind" below note,
            // now what you should do is to set isNetworkAccessAllowed to true
            // and make a new request.
        } else {
            //
        }
    }
})

As per mentioned in PHImageResultIsInCloudKey documentation, keep in mind that:

If true, no image was provided, because the asset data must be downloaded from iCloud. To download the data, submit another request, and specify true for the isNetworkAccessAllowed option.

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
  • So if I set is network access allowed then photo will be downloaded into original image without re-saving? – Richard Jan 14 '20 at 02:57