Observing photo album changes — iOS — Swift

Himal Madhushan
2 min readSep 27, 2017

--

In the previous article I wrote how to load videos from the albums. Now in this article I’m gonna write how to observe changes and make necessary changes in your application.

Incase if you have’t seen the previous article,

To observe changes, there is a protocol that we need to add and implement. It’sPHPhotoLibraryChangeObserver .

class ViewController: UIViewController, PHPhotoLibraryChangeObserver { }

As we saw in the previous article, we load the videos and we register our class to observe changes..

PHPhotoLibrary.shared().register(self)

Let’s observe…

public func photoLibraryDidChange(_ changeInstance: PHChange)

This is the method we are going to implement. It’s from the protocol PHPhotoLibraryChangeObserver .

let fetchResultChangeDetails = changeInstance.changeDetails(for: assetsFetchResult)

from the changeInstance we can gain the change details like what have been removed or added by giving the current fetched results assetsFetchResult . So it will know what’s new according to the old results.

if fetchResultChangeDetails is nil , there is no new changes. Make sure to check whether it’s been nil or not. Otherwise it will cause a crash.

assetsFetchResult = (fetchResultChangeDetails?.fetchResultAfterChanges)!

Reset the assetsFetchResult after fetchResultChangeDetails has new changes by getting (fetchResultChangeDetails?.fetchResultAfterChanges)! .

Then you will be able to see what have been added or removed by

let insertedObjects = fetchResultChangeDetails?.insertedObjectslet removedObjects = fetchResultChangeDetails?.removedObjects

There insertedObjects and removedObjects contains array of PHAsset .[PHAsset] .

Simply loop through the arrays and make necessary changes in your application.

So the final outcome as this..

func photoLibraryDidChange(_ changeInstance: PHChange) {    let fetchResultChangeDetails = changeInstance.changeDetails(for: assetsFetchResult)    guard (fetchResultChangeDetails) != nil else {        print("No change in fetchResultChangeDetails")        return;    }    print("Contains changes")    assetsFetchResult = (fetchResultChangeDetails?.fetchResultAfterChanges)!    let insertedObjects = fetchResultChangeDetails?.insertedObjects    let removedObjects = fetchResultChangeDetails?.removedObjects
}

Hope you know how to observe changes and apply necessary changes in your future applications.

Enjoy 😊

--

--