Profile
Back to NewsBack
Dev.to 4 min
Reader Mode
[iOS] PhotoKit Mistakes That Only Show Up With a Real Photo Library

[iOS] PhotoKit Mistakes That Only Show Up With a Real Photo Library

23 hours ago

PhotoKit code that works perfectly in the simulator, with its handful of sample photos, often falls apart on a real iPhone with 30,000 photos, half of them in iCloud.

Here are nine mistakes that are easy to make and hard to spot until real users hit them, and how to avoid each one.

1. Ignoring limited access

Since iOS 14, users can grant access to selected photos only. Many apps treat .limited like .denied, or like .authorized. Both are wrong.

let status = await PHPhotoLibrary.requestAuthorization(for: .readWrite)

switch status {
case .authorized: break                  // full library
case .limited:    break                  // only the photos the user picked: say so in your UI
case .denied, .restricted: break         // explain why, and link to Settings
case .notDetermined: break
@unknown default: break
}

With limited access, give users a way to change their selection:

PHPhotoLibrary.shared().presentLimitedLibraryPicker(from: viewController)

If you don't want iOS to prompt users to add more photos every time the app launches, add PHPhotoLibraryPreventAutomaticLimitedAccessAlert = YES to Info.plist and offer your own button instead.

2. Turning the fetch result into an array

PHFetchResult is lazy. It doesn't load 30,000 PHAsset objects until you ask for them. This line throws that away:

//  Loads every asset into memory at once
let all = (0..<result.count).map { result.object(at: $0) }

Index into the fetch result when you need an asset instead. A collection view only needs result.count and result.object(at: indexPath.item).

3. Asking for thumbnails in points instead of pixels

targetSize is in pixels. On a 3× device, a 100-point cell needs a 300-pixel image:

let scale = UIScreen.main.scale   // or the trait collection's displayScale
let targetSize = CGSize(width: cellSize.width * scale, height: cellSize.height * scale)

Too small and the grid looks blurry. Too large (for example PHImageManagerMaximumSize) and scrolling stutters and memory climbs.

4. Not expecting the completion handler to run twice

With .opportunistic delivery (the default), PhotoKit can call your handler twice: first with a fast, low-quality image, then with the final one.

manager.requestImage(for: asset, targetSize: size, contentMode: .aspectFill, options: options) { image, info in
    let isDegraded = (info?[PHImageResultIsDegradedKey] as? Bool) ?? false
    // Show the image either way, but only treat it as final when isDegraded == false.
}

If you hide a loading spinner, record analytics or save the result on the first call, you'll be working with the placeholder.

5. Forgetting to cancel requests on cell reuse

Scroll quickly through a grid and every cell fires a request. Without cancelling, images arrive for cells that have already been reused, and the wrong photo flashes into place.

override func prepareForReuse() {
    super.prepareForReuse()
    if let id = requestID { imageManager.cancelImageRequest(id) }
    imageView.image = nil
    representedAssetID = nil
}

Also check, in the completion handler, that the cell still shows the same asset (representedAssetID == asset.localIdentifier) before setting the image.

6. Not using PHCachingImageManager for grids

For scrolling grids, PHCachingImageManager can prepare thumbnails before cells appear:

cachingManager.startCachingImages(for: upcomingAssets, targetSize: size, contentMode: .aspectFill, options: nil)
cachingManager.stopCachingImages(for: assetsThatScrolledAway, targetSize: size, contentMode: .aspectFill, options: nil)

Update the cached range as the user scrolls (Apple's sample code compares the old and new visible rects), and use the same targetSize and options for caching and requesting, or the cache won't be used.

7. Treating iCloud photos as if they're on the device

With "Optimize iPhone Storage" turned on, many originals are only in iCloud. By default, PhotoKit won't download them, and your request returns nil.

let options = PHImageRequestOptions()
options.isNetworkAccessAllowed = true
options.progressHandler = { progress, error, stop, info in
    // Runs on a background queue: dispatch to the main queue to update the UI
}

Decide on purpose when downloading is worth it. Opening a photo full-screen: yes. Building a grid of thousands of thumbnails: no, because local thumbnails usually exist anyway.

Two things to design for:

  • The user can tap "Don't Allow". The call then throws, so treat that as a normal outcome, not an error message.
  • Deleted photos go to Recently Deleted and stay there for up to 30 days, so the storage isn't freed straight away. If your app shows "space saved", tell users to empty Recently Deleted if they need the space now.

Bonus: test with a real library

The simulator's sample photos hide almost every problem above. Test on a device with tens of thousands of photos, iCloud Photos turned on with "Optimize iPhone Storage", and limited access granted. That's where the bugs are.


The app that helped learn this tips Clean Kit, an iPhone photo and storage cleaner that runs entirely on-device. It's on the App Store.
For the curious, the app has a set of iPhone storage guides.

Chat with me