大幅に位置が変更した時のみ位置情報を取得する
大幅変更位置情報サービスは、標準位置情報サービスに代わるもので、消費電力を抑えつつ、多くのアプリケーションにとって十分な精度のデータを提供します。Wi-Fiを利用してユーザの位置を特定し、その位置の変更を報告します。これによりシステムは、電力使用量をより積極的に管理することができます。さらに、新しい位置データを配送するために、現在一時停止中または実行していないiOSアプリケーションを「起こす」ことも可能です。
UI要素の用意
Label * 2(緯度・経度用)
Button * 2(開始・終了用)
をストーリーボードに配置し、Outlet作成
ViewController.swift
class ViewController: UIViewController {
@IBOutlet weak var latitudeLabel: UILabel!
@IBOutlet weak var longitudeLabel: UILabel!
@IBOutlet weak var startButton: UIButton!
@IBOutlet weak var stopButton: UIButton!
位置情報利用準備
Info.plistのRequired device capabilitiesにlocation-servicesとgps追加
Info.plistのInformation Property ListにNSLocationAlwaysUsageDescriptionを追加して、許可を求めるダイアログに表示する文字列を設定
ViewController.swiftを編集
ViewController.swift
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
var myLocationManager: CLLocationManager!
/*
(中略)
*/
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()
}
if !CLLocationManager.locationServicesEnabled() {
return
}
詳しくは現在地の緯度・経度表示参照
大幅変更位置情報サービス開始
スタートボタンのアクション作成
ViewController.swift
if !CLLocationManager.locationServicesEnabled() {
return
}
}
@IBAction func onClickStartButton(sender: UIButton) {
myLocationManager.startMonitoringSignificantLocationChanges()
}
ストップボタンのアクション作成
ViewController.swift
myLocationManager.startMonitoringSignificantLocationChanges()
}
@IBAction func onClickStopButton(sender: UIButton) {
myLocationManager.stopMonitoringSignificantLocationChanges()
}
位置情報取得成功時の動作作成
ViewController.swift
myLocationManager.stopMonitoringSignificantLocationChanges()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let lastLocation = locations.last
if let last = lastLocation {
let eventDate = last.timestamp
if abs(eventDate.timeIntervalSinceNow) < 15.0 {
if let location = manager.location {
latitudeLabel.text = "緯度:\(location.coordinate.latitude)"
longitudeLabel.text = "経度:\(location.coordinate.longitude)"
}
}
}
}
位置情報取得失敗時の動作作成
ViewController.swift
longitudeLabel.text = "経度:\(location.coordinate.longitude)"
}
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("error")
}