Filtering photo library by picture size with Photos framework

1.2k views Asked by At

I am building iOS app for selecting screenshots from user's photo library. The app works, except I can display all photos and I need only screenshots. To detect screenshots I want to match images size with the screen size.

var userScreenshots: PHFetchResult!

let screenWidth = view.bounds.size.width * 2
let screenHeight = view.bounds.size.height * 2

let options = PHFetchOptions()
// Following line needs to be changed —>
options.predicate = NSPredicate(format: "(pixelWidth & %d) != 0 || (pixelHeight & %d) != 0", screenWidth, screenHeight)

options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]

userScreenshots = PHAsset.fetchAssetsWithOptions(options)

Crash:

2015-06-22 23:00:24.540 Altershot[95046:24515142] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unsupported predicate in fetch options: pixelWidth & 0 != 0'

Please explain how to define this predicate properly.

1

There are 1 answers

0
Yurkevich On BEST ANSWER

Here is correct code. Note, that's instead of magic number 2 there's scale universal property because of iPhone 6 Plus has scale of 3. I also included landscape screenshots, thanks for the comments. Also, screen size formula was improved to prepare it for iOS 9 multitasking.

var userScreenshots: PHFetchResult!

let scale = UIScreen.mainScreen().scale
let screenWidth = UIScreen.mainScreen().bounds.width * scale
let screenHeight = UIScreen.mainScreen().bounds.height  * scale

let options = PHFetchOptions()
options.predicate = NSPredicate(format: "(pixelHeight == %d AND pixelWidth == %d) OR (pixelHeight == %d AND pixelWidth == %d)", argumentArray: [screenHeight, screenWidth, screenWidth, screenHeight])

options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]

userScreenshots = PHAsset.fetchAssetsWithOptions(options)