How to observe photo library changes even when app is closed?

1.8k Views Asked by At

I need to be notified when a photo/video is taken, even when my app is closed.

Does anybody know how apps like Google Photos achieve this in iOS?

So far, I have implemented and registered PHPhotoLibraryChangeObserver however photoLibraryDidChange only gets called if my app is in background mode but not if user manually closes the app.

PHPhotoLibraryChangeObserver implementation:

import UIKit
import Photos

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, PHPhotoLibraryChangeObserver {

    // ...

    var assetsFetchResult = PHFetchResult<PHAsset>()

    func applicationDidEnterBackground(_ application: UIApplication) {
        PHPhotoLibrary.requestAuthorization { (authorizationStatus) in
            if (authorizationStatus == .authorized){

                assetsFetchResult = getAssets()!

                PHPhotoLibrary.shared().register(self)
            }
        }
    }

    func getAssets() -> PHFetchResult<PHAsset>?{
        return PHAsset.fetchAssets(with: PHFetchOptions())
    }

    func photoLibraryDidChange(_ changeInstance: PHChange) {
        print("photoLibraryDidChange")
        DispatchQueue.main.async {
            let fetchResultChangeDetails = changeInstance.changeDetails(for: self.assetsFetchResult)

            guard (fetchResultChangeDetails) != nil else {
                return
            }

            self.assetsFetchResult = (fetchResultChangeDetails?.fetchResultAfterChanges)!

            let insertedObjects = fetchResultChangeDetails?.insertedObjects

            let changedObjects = fetchResultChangeDetails?.changedObjects

            let removedObjects = fetchResultChangeDetails?.removedObjects

            // ...
        }
    }
}

I have also tried to achieve this through Background fetch.

First I enabled the background fetch capability in Project Settings > Capabilities > Background Modes.

Then I tested it by:

  • Running the app from Xcode, then clicking on Debug > Simulate Background Fetch
  • Duplicating my Scheme and enabling the 'Launch due to a background fetch event' option

However there seems to be no guarantees on when Background Fetch will be called on a real life scenario and I need it to be called as soon as possible after a photo/video is taken.

https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623125-application

Background fetch implementation:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {        
    UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalMinimum)
    return true
}

func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    //if application.backgroundRefreshStatus == .available && application.applicationState == .background {
        if let newData = getNewAssets() {
            newData.enumerateObjects { (object, _, _) in
                if let asset = object as? PHAsset {
                    // ...
                }
            }
            completionHandler(.newData)
            return
        }
    //}
    completionHandler(.noData)
}

func getNewAssets() -> PHFetchResult<PHAsset>?{
    let options = PHFetchOptions()

    if let lastAutoUpload = UserSession.getLastAutoUploadDate(){
        options.predicate = NSPredicate(format: "(modificationDate > %@)", lastAutoUpload as CVarArg)
    }
    return PHAsset.fetchAssets(with: options)
}

Environment: - Swift 4.2 - Xcode 10.1 - Testing on real devices: iPhone 6 and iPad Mini 3 (iOS 12)

0

There are 0 best solutions below