在Swift中获取PHAsset的位置

问题描述 投票:6回答:4

出于某种原因,location上的PHAsset属性仅在Objective-c中暴露,而不在Swift中暴露。

Documentation: PHAsset.location

为了解决这个问题,我想我可以创建一个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

ios objective-c swift ios8 phasset
4个回答
4
投票

事实证明,答案非常简单。问题是Swift文件不知道CLLocation是什么,因此拒绝导入该函数。导入CoreLocation解决了这个问题。

import CoreLocation

LocationGetter.locationForAsset(ass)

编辑:苹果已经将.location列为PHAsset的吸气剂。现在获得位置就像asset.location一样简单。


0
投票

对于那些希望打印每个照片位置的人来说,这里是:

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

0
投票

你可以像这些代码行一样轻松地检索每个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)
    }
}

0
投票

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.
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.