Getting PHAsset Location in Swift

For some reason, the location property on PHAsset only appears in Objective-c, not Swift.

Documentation: PHAsset.location

To get around this, I thought I could create an 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' has no member named 'locationForAsset'

Bonus question: why didn’t Apple show location fast?

+6
source share
3 answers

It turns out that the answer is really simple. The problem is that the Swift file does not know what CLLocation , and thus refuses to import this function. Importing CoreLocation solves the problem.

 import CoreLocation LocationGetter.locationForAsset(ass) 

EDIT: Apple has since included .location as a recipient on PHAsset . Getting a location is now as easy as asset.location .

+4
source

For those who want to print each location of a photograph, here it is:

 var allAssets = PHAsset.fetchAssetsWithMediaType(PHAssetMediaType.Image, options: nil) allAssets.enumerateObjectsUsingBlock({asset, index, stop in if let ass = asset as? PHAsset{ println(ass.location) } } 
0
source

You can get the location of each PHAsset as simple as these lines of code:

 let phFetchRes = PHAsset.fetchAssets(with: PHAssetMediaType.image , options: nil) // Fetch all PHAssets of images from Camera roll let asset = phFetchRes.object(at: 0) // retrieve cell 0 as a asset let location = asset.location // retrieve the location print(location) // Print result 

Or, if you want to get all locations from PHAsset, you can use the codes above, for example:

 let phFetchRes = PHAsset.fetchAssets(with: PHAssetMediaType.image , options: nil) // Fetch all PHAssets of images from Camera roll phFetchRes.enumerateObjectsUsingBlock({asset, index, stop in if let ass = asset as? PHAsset{ println(ass.location) } } 
0
source

Source: https://habr.com/ru/post/1201468/


All Articles