LoginSignup
4
3

More than 5 years have passed since last update.

[Swift]imagePickerControllerで写真のexif情報(位置情報)を取得するサンプル

Last updated at Posted at 2018-06-28

【写真のexif情報を取得方法】


前提条件


info.plistの設定
import Photos
UIImagePickerDelegate
imagePickerControllerの呼び出し

以下、写真が押された時に呼ばれる関数です。

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    // 選択したアイテムの元のバージョンのAssets Library URL
    let assetUrl = info[UIImagePickerControllerReferenceURL] as! URL
    // PHAsset = Photo Library上の画像、ビデオ、ライブフォト用の型
    let result = PHAsset.fetchAssets(withALAssetURLs: [assetUrl], options: nil)
    let asset = result.firstObject
    // コンテンツ編集セッションを開始するためのアセットの要求
    asset?.requestContentEditingInput(with: nil, completionHandler: { contentEditingInput, info in
        // contentEditingInput = 編集用のアセットに関する情報を提供するコンテナ
        let url = contentEditingInput?.fullSizeImageURL
        // 対象アセットのURLからCIImageを生成
        let inputImage = CIImage(contentsOf: url!)!
        // CIImageのpropertiesから画像のメタデータのなかのGPSを取得する
        if inputImage.properties["{GPS}"] as? Dictionary<String,Any> == nil {
            print("この写真にはGPS情報がありません")
        } else {
            let gps = inputImage.properties["{GPS}"] as? Dictionary<String,Any>
            var latitude = gps!["Latitude"] as! Double
            let latitudeRef = gps!["LatitudeRef"] as! String
            var longitude = gps!["Longitude"] as! Double
            let longitudeRef = gps!["LongitudeRef"] as! String
            if latitudeRef == "S" {
                latitude = latitude * -1
            }
            if longitudeRef == "W" {
                longitude = longitude * -1
            }
            print(latitude)
            print(longitude)
        }
    })
    picker.dismiss(animated: true, completion: nil)
}

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3