LoginSignup
16
12

More than 5 years have passed since last update.

バックグラウンドで位置情報を取得

Last updated at Posted at 2016-10-04

バックグラウンドで位置情報を取得

自分用のメモとして

追記(2016/10/15)

バッググラウンドで取った位置情報をFirebaseのrealtimeDBに送信していたが、
メールアドレス認証(Auth)を付けたら、全く動かなくなった

原因調査中、分かり次第別記事にて解説入れます!
原因
-FirebaseのDBのルールをいじったから
-本記事のviewControllerの前に認証用のviewControllerを追加したから
-認証が悪い

追記(2016/10/21)

くだらない理由で解決した

info.plistのPrivacy - Location Always Usage Descriptionを
Location Always Usage Descriptionと書き換えていた。
この辺のパーミッション系はいじっちゃダメってことでした。

環境

iOS10 Xcode8 Swift3

初期設定

ターゲット->backgroudModeをON->Backgroud Fetchにチェックを入れる

スクリーンショット 2016-10-04 14.20.18.png

info.plistにPrivacy - Location Always Usage Descriptionを追加
Valueにはパーミッションのアラートに表示するテキストを入力

スクリーンショット 2016-10-21 8.54.23.png

ViewController.swift

ViewController.swift
import UIKit
import CoreLocation

class ViewController: UIViewController,CLLocationManagerDelegate {    
    var myLocationManager: CLLocationManager!
    var myLatitude       : String = ""
    var myLongitude      : String = ""

    //Success get location
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = manager.location {
            self.myLatitude  = "\(location.coordinate.latitude)"
            self.myLongitude = "\(location.coordinate.longitude)"

            print("\(self.myLatitude):\(self.myLongitude)")

        }
    }

    //Cant get location
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("error")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let status = CLLocationManager.authorizationStatus()
        if status == CLAuthorizationStatus.restricted || status == CLAuthorizationStatus.denied {
            return
        }

        myLocationManager = CLLocationManager()
        myLocationManager.delegate = self

        //
        if status == CLAuthorizationStatus.notDetermined {
            myLocationManager.requestAlwaysAuthorization()
            myLocationManager.startMonitoringSignificantLocationChanges()
        }else{
            myLocationManager.startMonitoringSignificantLocationChanges()
        }

        //
        if !CLLocationManager.locationServicesEnabled() {
            return
        }

        myLocationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
        myLocationManager.distanceFilter = 100   
    }
}

参考

バックグラウンドで位置情報を取得する(CoreLocation::CLLocationManager)
http://qiita.com/shngt/items/6687edeb055113e5fd70
【iOS 9対応】知っておきたい位置情報周りの変更点
http://qiita.com/koogawa/items/024b00173561ed06ce9a

16
12
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
16
12