Swift에서 CLLocationManagerDelegate 메소드 구현
-
21-12-2019 - |
문제
저는 한동안 이것을 작동시키려고 노력해 왔으며 Swift에서 CLLocationManagerDelegate 메소드를 어떻게 사용할 수 있는지 묻기 위해 여기에 왔습니다.나는 이것을 내 수업의 맨 위에 두었습니다.
var locationManager = CLLocationManager()
나는 다음을 내 viewDidLoad
방법:
locationManager.delegate = self
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
그리고 나는 아무 소용없이 이러한 대리자 메서드를 사용해 보았습니다.
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: AnyObject[]!) {
locationReceived = true
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
locationReceived = false
}
또한 함수 앞에 @선택 사항을 사용해 보았으나 Xcode에서 컴파일러 오류가 발생했습니다.어떤 아이디어가 있나요?
해결책
당신은 NSLocationAlwaysUsageDescription
또는 NSLocationWhenInUseUsageDescription
plist의 키가 아직 없다면 이제 필수입니다.
iOS8+에서는 위치를 사용하려면 이 두 문자열 중 하나를 설정해야 합니다.어떤 것을 사용하는지는 위치를 묻는 방법에 따라 다릅니다.
사용
NSLocationAlwaysUsageDescription
앱이 열려 있지 않거나 사용 중이 아닐 때에도 기기의 위치를 사용하려는 앱의 경우.사용
NSLocationWhenInUseUsageDescription
앱이 열려 있고 사용 중일 때만 기기의 위치를 사용하려는 앱의 경우.
메모: 문자열을 추가할 때 빌드하고 실행하기 전에 기기에서 앱을 삭제하고 새로 설치하도록 하세요.iOS8로 업그레이드하기 전에 앱이 위치를 사용하도록 승인된 경우 다시 권한을 요청하지 않으며 해당 문자열을 설정한 것도 표시되지 않는 것 같습니다.삭제하고 새로 설치하면 해결됩니다.
문자열 중 하나를 설정하면 설치/처음 사용 시 다음 줄에 따라 팝업이 표시됩니다."앱을 사용하지 않을 때에도 "ThisApp"이 사용자의 위치에 액세스하도록 허용합니다."
여기 스크린샷 ~의 plist 파일.
다른 팁
첫 번째이 두 줄을 Plist File
에 추가하십시오.1) nslocationWhenUnsUsageDescription
2) nslocationalwaysudedescription
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate
var seenError : Bool = false
var locationFixAchieved : Bool = false
var locationStatus : NSString = "Not Started"
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
}
func initLocationManager() {
seenError = false
locationFixAchieved = false
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.locationServicesEnabled
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
}
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)")
}
}
. 사용자 현재 위치를 가져 오려면 -
1 단계 : let locationManager = CLLocationManager() // make object of CLLocationManager class.
2 단계 : In viewDidLoad instantiate the CLLocationManager class like,
// 백그라운드에서 사용하기
self.locationManager.requestAlwaysAuthorization()
// For use in foreground
self.locationManager.requestWhenInUseAuthorization()
if (CLLocationManager.locationServicesEnabled())
{
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
.
3 단계 : 이제 CLLocationManager
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var locValue:CLLocationCoordinate2D = manager.location.coordinate
println("locations = \(locValue.latitude) \(locValue.longitude)")
}
.
4 단계 :
IOS 8에서와 같이 INFO.PLIST에 NSLocationAlwaysUsageDescription
를 추가하는 것을 잊지 마십시오.이를 추가하려면 필수입니다.그러면 사용자의 위치를 사용할 수있는 권한이 묻습니다.
나는 같은 문제가있었습니다.DidupDatiLocations - 작동하지 않았습니다.앱을 실행하십시오. 설정 페이지 -> 개인 정보 보호 -> 위치로 이동하여 위치 서비스를 끕니다.DidfailWithError는 원재하지 않는 위치 서비스에 대한 오류를 잡습니다.그런 다음 켜십시오.그 순간 DidupDatiLocations가 위치를 잡을 것입니다.
이것은 오래된 스레드의 약간이지만, 위의 것들 중 어느 것도 swift 2.2 xcode 7.3.1에서 나에게 일했습니다.
문제는 내가 사용하고있는 것입니다 :
func locationManager(manager: CLLocationManager!, didUpdateLocation locations: [AnyObject]!) {
print("Got location")
locationManager.stopUpdatingLocation()
}
.
그리고 이것이 결코 부름을받지 못했습니다.내가 바꿨을 때 :
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("Got location")
locationManager.stopUpdatingLocation()
}
.
모든 것이 효과가있었습니다.[AnyObject]
를 사용할 때 대리인이 호출되지 않는 것처럼 보입니다.