For some reason the location
property on a PHAsset
is only exposed in Objective-c and not in Swift.
Documentation: PHAsset.location
To work around it, I figured I could create a Objective-C class whose sole purpose is to extract the location and import it into Swift.
LocationGetter.h
@interface LocationGetter : NSObject
+ (CLLocation *)locationForAsset:(PHAsset *) asset;
@end
LocationGetter.m
@implementation LocationGetter
+ (CLLocation *)locationForAsset:(PHAsset *) asset {
return [asset location];
}
@end
So far so good, but when I try to use it in Swift:
LocationGetter.locationForAsset(ass)
'LocationGetter.Type' does not have a member named 'locationForAsset'
Bonus question: Why on earth didn't Apple expose location
in swift?
You can retrieve the location of every
PHAsset
as easy as these lines of code:Or if you want to retrieve all of locations from PHAsset you can use above codes like this:
It turns out that the answer is really simple. The problem is that the Swift file don't know what a
CLLocation
is, and thus refuses to import that function. ImportingCoreLocation
solves the issue.EDIT: Apple has since included
.location
as a getter on thePHAsset
. Getting the location is now as easy asasset.location
.iOS12, Swift 4 - Get location from Photo Library Moment, if asset itself does not have location.
I noticed that sometimes, the location of the asset itself was nil, while, in the Photo's app, the asset was grouped into a moment that had a location. If I had to guess, I'd say the photo app groups photos by date into a moment and then if at least one of those photos has a location, the moment is given a location.
Now, how to get the location of that moment, if the location of the asset itself is nil? Like this:
For those who looking to print each photo location, here it is: