Sorting photos exactly like native photoapp using PhotoKit
As @knutigro mentioned the solution is to use PHFetchResult
with the default options i.e. by passing in nil
for the options
parameter:
var fetchResult: PHFetchResult!
override func viewDidLoad() {
super.viewDidLoad()
fetchResult = PHAsset.fetchAssetsWithMediaType(.Image, options: nil)
}
But the next step is reversing the sort results so that the most recent image is first. There isn't an easy way to reverse the results in PHFetchResult so I used the following method:
func assetAtIndex(index: Int) -> PHAsset {
// Return results in reverse order
return fetchResult[fetchResult.count - index - 1] as! PHAsset
}
You may try using two sort descriptors :
NSSortDescriptor sortDesc1 = [NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
NSSortDescriptor sortDesc2 = [NSSortDescriptor sortDescriptorWithKey:@"modificationDate" ascending:NO]];
options.sortDescriptors = @[sortDesc1, sortDesc2];
Haven't tested, just thought it might work.
swift 3
let fetchOptions = PHFetchOptions()
let sortOrder = [NSSortDescriptor(key: "creationDate", ascending: false)]
fetchOptions.sortDescriptors = sortOrder
I just found out that to copy the exact behaviour of the native photopicker the sollution was to remove my custom sortDescriptior
and just use the PHFetchResult
with default behaviour. It seeme so obvious now after discovering that.