[英]Getting the location of a PHAsset in Swift
由于某种原因, PHAsset
上的location
属性仅在Objective-c中公开,而不在Swift中公开。
为了解决这个问题,我想我可以创建一个Objective-C类,其唯一目的是提取位置并将其导入Swift。
LocationGetter.h
@interface LocationGetter : NSObject
+ (CLLocation *)locationForAsset:(PHAsset *) asset;
@end
LocationGetter.m
@implementation LocationGetter
+ (CLLocation *)locationForAsset:(PHAsset *) asset {
return [asset location];
}
@end
到目前为止一切都那么好,但是当我尝试在Swift中使用它时:
LocationGetter.locationForAsset(ass)
'LocationGetter.Type'没有名为'locationForAsset'的成员
奖金问题:为什么苹果公司没有在快速公开location
?
事实证明,答案非常简单。 问题是Swift文件不知道CLLocation
是什么,因此拒绝导入该函数。 导入CoreLocation
可以解决此问题。
import CoreLocation
LocationGetter.locationForAsset(ass)
编辑:苹果公司,此后他先后.location
作为对一个getter PHAsset
。 获取位置现在就像asset.location
一样简单。
对于那些希望打印每个照片位置的人来说,这里是:
var allAssets = PHAsset.fetchAssetsWithMediaType(PHAssetMediaType.Image, options: nil)
allAssets.enumerateObjectsUsingBlock({asset, index, stop in
if let ass = asset as? PHAsset{
println(ass.location)
}
}
您可以像这些代码行一样轻松检索每个PHAsset
的位置:
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
或者,如果要从PHAsset中检索所有位置,可以使用以下代码:
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)
}
}
iOS12,Swift 4 - 如果资产本身没有位置,从Photo Library Moment获取位置。
我注意到有时候,资产本身的位置是零,而在Photo的应用程序中,资产被分组到一个有位置的时刻。 如果我不得不猜测,我会说照片应用程序按照日期将照片分组到片刻,然后如果这些照片中至少有一张有位置,则会给出一个位置。
现在,如果资产本身的位置为零,如何获得该时刻的位置? 像这样:
if let asset = info[UIImagePickerController.InfoKey.phAsset] as? PHAsset {
if let photoCoordinate = asset.location?.coordinate {
// The asset itself has a location. Do something with it.
}
else {
// The asset itself does not have a location
// find the moments containing the asset
let momentsContainingAsset = PHAssetCollection.fetchAssetCollectionsContaining(asset, with: .moment, options: nil)
for i in 0..<momentsContainingAsset.count {
let moment = momentsContainingAsset.object(at: i)
if let momentCoordinate = moment.approximateLocation?.coordinate {
// this moment has a location. Use it as you wish.
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.