web-dev-qa-db-ja.com

CLLocationManagerでSwiftでLocationユーザーを取得する方法は?

私のView Controllerにこのコードがありますが、これは機能しません:

  import UIKit
  import CoreLocation

  class ViewController: UIViewController, CLLocationManagerDelegate {

   var location: CLLocationManager!

  override func viewDidLoad() {
     super.viewDidLoad()

     location=CLLocationManager()
     location.delegate = self
     location.desiredAccuracy=kCLLocationAccuracyBest
     location.startUpdatingLocation()
 }

  func locationManager(location:CLLocationManager, didUpdateLocations locations:AnyObject[]) {
     println("locations = \(locations)")
     label1.text = "success"
 }

私は他の投稿で読む方法の許可を持っています。しかし、私は決して、printlnを取得しません。

ありがとう!!

14
user3745888

最初にこの2行をplistファイルに追加します

1)NSLocationWhenInUseUsageDescription

2)NSLocationAlwaysUsageDescription

次に、これは完全に実装されたクラス作業です

import UIKit 
import CoreLocation

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {

var window: UIWindow?
var locationManager: CLLocationManager!
var seenError : Bool = false
var locationFixAchieved : Bool = false
var locationStatus : NSString = "Not Started"

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
    initLocationManager();
    return true
}

// Location Manager helper stuff
func initLocationManager() {
    seenError = false
    locationFixAchieved = false
    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.locationServicesEnabled
    locationManager.desiredAccuracy = kCLLocationAccuracyBest

    locationManager.requestAlwaysAuthorization()
}

// Location Manager Delegate stuff

func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
    locationManager.stopUpdatingLocation()
    if (error) {
        if (seenError == false) {
            seenError = true
           print(error)
        }
    }
}

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: AnyObject[]!) {
    if (locationFixAchieved == false) {
        locationFixAchieved = true
        var locationArray = locations as NSArray
        var locationObj = locationArray.lastObject as CLLocation
        var coord = locationObj.coordinate

        println(coord.latitude)
        println(coord.longitude)
    }
}

func locationManager(manager: CLLocationManager!,
    didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        var shouldIAllow = false

        switch status {
        case CLAuthorizationStatus.Restricted:
            locationStatus = "Restricted Access to location"
        case CLAuthorizationStatus.Denied:
            locationStatus = "User denied access to location"
        case CLAuthorizationStatus.NotDetermined:
            locationStatus = "Status not determined"
        default:
            locationStatus = "Allowed to location Access"
            shouldIAllow = true
        }
        NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil)
        if (shouldIAllow == true) {
            NSLog("Location to Allowed")
            // Start location services
            locationManager.startUpdatingLocation()
        } else {
            NSLog("Denied access: \(locationStatus)")
        }
}
}
19

Swift 3でユーザーの場所を取得するための簡単な手順を次に示します

1)最初に、この行を説明付きのplistファイルに追加します

 NSLocationWhenInUseUsageDescription

2)プロジェクトにCoreLocation.frameworkを追加します([ビルドフェーズ]セクションの[ライブラリとバイナリをリンク]セクション)

3)AppDelegateクラス内

   import CoreLocation

4)locationManagerオブジェクトを次のように作成します

    var locationManager:CLLocationManager!

5)didFinishLaunchingWithOptionsに次のコードを記述します

    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.distanceFilter = 200
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()

6)次のようにCLLocationManagerDelegateデリゲートを確認します

   class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate

7)ユーザーの位置を取得するためのCLLocationManagerDelegateデリゲートメソッドを記述する

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {

    print("location error is = \(error.localizedDescription)")

}


func locationManager(_ manager: CLLocationManager,
                     didUpdateLocations locations: [CLLocation]) {

    let locValue:CLLocationCoordinate2D = (manager.location?.coordinate)!


    print("Current Locations = \(locValue.latitude) \(locValue.longitude)")
}
5
Devendra Singh

ロケーションを明示的にアンラップされたオプション(CLLocationManager!)として宣言しているため、jhurrayによって提案されたinitメソッドまたは次のようにインラインで初期化子が必要です。

var location: CLLocationManager! = nil

IOS 8には、CoreLocationを使用する許可をユーザーに照会するための新しい要件があるなど、他にも考えられる問題があることに注意してください。詳細は question をご覧ください。

2
David Berry

これは上記と同じコードですが、この投稿の日付の時点でSwiftで動作するようにクリーンアップされています。これは私にとってはうまくいきました。

元のポスターへの称賛。

(注意、これはあなたの位置情報を処理するために使用するクラスに付けてください。)

var lastLocation = CLLocation()
var locationAuthorizationStatus:CLAuthorizationStatus!
var window: UIWindow?
var locationManager: CLLocationManager!
var seenError : Bool = false
var locationFixAchieved : Bool = false
var locationStatus : NSString = "Not Started"

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    
    
    self.initLocationManager()
    
}
    // Location Manager helper stuff
    func initLocationManager() {
        seenError = false
        locationFixAchieved = false
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        
        locationManager.requestAlwaysAuthorization()
    }
    
    // Location Manager Delegate stuff
    
    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
        locationManager.stopUpdatingLocation()
        if ((error) != nil) {
            if (seenError == false) {
                seenError = true
                print(error)
            }
        }
    }
    
    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        if (locationFixAchieved == false) {
            locationFixAchieved = true
            var locationArray = locations as NSArray
            var locationObj = locationArray.lastObject as CLLocation
            var coord = locationObj.coordinate
            
            println(coord.latitude)
            println(coord.longitude)
        }
    }
    
    func locationManager(manager: CLLocationManager!,  didChangeAuthorizationStatus status: CLAuthorizationStatus) {
            var shouldIAllow = false
            
            switch status {
            case CLAuthorizationStatus.Restricted:
                locationStatus = "Restricted Access to location"
            case CLAuthorizationStatus.Denied:
                locationStatus = "User denied access to location"
            case CLAuthorizationStatus.NotDetermined:
                locationStatus = "Status not determined"
            default:
                locationStatus = "Allowed to location Access"
                shouldIAllow = true
            }
            NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil)
            if (shouldIAllow == true) {
                NSLog("Location to Allowed")
                // Start location services
                locationManager.startUpdatingLocation()
            } else {
                NSLog("Denied access: \(locationStatus)")
            }
    }

Func locationManager(manager:CLLocationManager、didUpdateLocations locations:[CLLocation]){

0
MacInnis

ViewControllerで次のことを行う[Swiftの使用]-

  class ViewController:     
  UIViewController,MKMapViewDelegate,CLLocationManagerDelegate {


  var locationManager: CLLocationManager?
  var usersCurrentLocation:CLLocationCoordinate2D?

  override func viewDidLoad() {
    super.viewDidLoad()

    self.locationManager = CLLocationManager()

    if CLLocationManager.authorizationStatus() == .NotDetermined{
        locationManager?.requestAlwaysAuthorization()
    }

    locationManager?.desiredAccuracy = kCLLocationAccuracyBest
    locationManager?.distanceFilter = 200
    locationManager?.delegate = self
    startUpdatingLocation()

    usersCurrentLocation = CLLocationCoordinate2DMake(LATTITUDE, LONGITUDE)
    let span = MKCoordinateSpanMake(0.005, 0.005)
    let region = MKCoordinateRegionMake(usersCurrentLocation!, span)
    mapview.setRegion(region, animated: true)
    mapview.delegate = self
    mapview.showsUserLocation = true

}

// MARK:CLLocationManagerDelegateメソッド

func startUpdatingLocation() {
    self.locationManager?.startUpdatingLocation()
}

func stopUpdatingLocation() {
    self.locationManager?.stopUpdatingLocation()
}

// MARK:MKMapViewDelegate

func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation){
    mapview.centerCoordinate = userLocation.location!.coordinate
    mapview.showsUserLocation = true
    regionWithGeofencing()

}
0
be.with.veeresh

初期化関数が必要です。

Init(coder :)およびinit(nibName:bundle :)をオーバーライドし、必要なカスタムinitを追加します。

ロケーションはオプションではないと述べたため、スーパーinitがすべてのinit関数で呼び出す前に、ロケーションを初期化する必要があります。

func init() {
...
location = CLLocationManager()
// either set delegate and other stuff here or in viewDidLoad
super.init(nibName:nil, bundle:nil)
// other initialization below

}
0
jhurray