gpt4 book ai didi

ios - 如何使用 swift 在 iOS7 中调用 CLLocation Manager 委托(delegate)方法

转载 作者:行者123 更新时间:2023-11-28 12:48:39 25 4
gpt4 key购买 nike

我正在使用 swift 2.2 并创建了一个将位置发送到 mdm 服务器的应用程序。我已将该类声明为 NSObject 的子类,并包含了 CLLOcationManagerDelegate。但是没有调用 didUpdateLocations() 和 didUpdateToLocation() 等方法。我没有使用任何按钮或发送位置的 View 中的任何内容。我希望应用程序在更新位置时将位置发送到服务器。这是我的代码。

class LocationProcessHandler: NSObject , CLLocationManagerDelegate{

var location = CLLocationManager()
func startLocationUpdates() {



NSLog("It entered the start location updates method of the location process handler")
if (!(CLLocationManager.locationServicesEnabled()) || (CLLocationManager.authorizationStatus() != CLAuthorizationStatus.Denied )) {

NSLog("It Entered to create the managed app feedback ")
let persist = Persistence()

let json: [NSObject : AnyObject] = [
"IsLocationSettingsEnabled" : "\(0)",mdmiosagent_Constants.MESSAGETYPEKEY : mdmiosagent_Constants.LOCATIONMSGTYPEKEY,mdmiosagent_Constants.UDIDKEY : persist.getObject(mdmiosagent_Constants.UDIDKEY),"TimeStamp" : "\(self.toLocalTime())"
]
let userDefaults : NSUserDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(json, forKey: mdmiosagent_Constants.MANAGED_APP_FEEDBACK)
userDefaults.synchronize()
NSLog("The dict to be sent as managed app feedback is \(json)")
do {
let jsonData : NSData = try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted)
let wrapper = HttpWrapper()
wrapper.silentPostData(serverurl: mdmiosagent_Constants.NATIVE_APP_SERVLET, urldata: jsonData)
} catch {
NSLog("json error")
}

}
location.delegate = self
location.desiredAccuracy = kCLLocationAccuracyNearestTenMeters


if #available(iOS 8.0, *) {
location.requestWhenInUseAuthorization()
}
location.delegate = self
location.startUpdatingLocation()
NSLog("Started to monitor the significant location Changes")
location.stopMonitoringSignificantLocationChanges()
location.startMonitoringSignificantLocationChanges()

}

func location(manager: CLLocationManager!,
didChangeAuthorizationStatus status: CLAuthorizationStatus) {
var shouldIAllow = false
var locationStatus = String()
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
location.startUpdatingLocation()
} else {
NSLog("Denied access: \(locationStatus)")
}
}

func processMessage (dict : NSDictionary) {
let msgType : NSString = dict.objectForKey(mdmiosagent_Constants.MESSAGETYPEKEY) as! String
if (msgType.isEqual(mdmiosagent_Constants.MONITORREGIONKEY)) {
// self.startmonitoring(dict)
}
}

func stopLocationUpdates() {
location.stopMonitoringSignificantLocationChanges()
location.stopUpdatingLocation()

}
// this particular function is Used with two commands but not used as of now
func startmonitoring (currentLocation : CLLocation) {
let latitude : Double = currentLocation.coordinate.latitude
let Longitude : Double = currentLocation.coordinate.longitude
let regionID = "GeoFenceTrack"
let region: CLCircularRegion = CLCircularRegion.init(center: CLLocationCoordinate2DMake(latitude, Longitude), radius: Double(mdmiosagent_Constants.LOCATIONRADIUS)! , identifier: regionID)
location.delegate = self
location.desiredAccuracy = kCLLocationAccuracyBest
location.stopMonitoringForRegion(region)
}

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
NSLog("Location Updated")
let persist = Persistence()
let currentLocation : CLLocation = locations[0]
let latitude : Double = currentLocation.coordinate.latitude
let Longitude : Double = currentLocation.coordinate.longitude
let regionID = "GeoFenceTrack"
let region : CLCircularRegion = CLCircularRegion.init(center: CLLocationCoordinate2DMake(latitude, Longitude), radius: Double(persist.getObject(mdmiosagent_Constants.LOCATIONRADIUS))!, identifier: regionID)
self.sendLocation(currentLocation)
location.desiredAccuracy = kCLLocationAccuracyHundredMeters
location.delegate = self
location.stopMonitoringForRegion(region)
}

func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
NSLog("Location Updated")

let latitude : Double = newLocation.coordinate.latitude
let Longitude : Double = newLocation.coordinate.longitude

let regionID = "GeoFenceTrack"
let region : CLCircularRegion = CLCircularRegion.init(center: CLLocationCoordinate2DMake(latitude, Longitude), radius: Double(mdmiosagent_Constants.LOCATIONRADIUS)!, identifier: regionID)
location.startMonitoringForRegion(region)
let currentLocation = newLocation
self.sendLocation(currentLocation)
}

func sendLocation ( currentLocation : CLLocation ) {
let latitude: String = "\(Int(currentLocation.coordinate.latitude))"
let longitude : String = "\(Int(currentLocation.coordinate.longitude))"

let json: [NSObject : AnyObject] = [
mdmiosagent_Constants.MESSAGETYPEKEY : mdmiosagent_Constants.LOCATIONMSGTYPEKEY,
mdmiosagent_Constants.LATITUDEKEY : latitude,
mdmiosagent_Constants.LONGITUDEKEY : longitude,
mdmiosagent_Constants.UDIDKEY : defaults.UDID,
"TimeStamp" : "\(self.toLocalTime())",
"IsLocationSettingsEnabled" : "\(CLLocationManager.locationServicesEnabled())"
]

let userDefaults : NSUserDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(json, forKey: mdmiosagent_Constants.MANAGED_APP_FEEDBACK)
userDefaults.synchronize()
do {
let jsonData : NSData = try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted)
let wrapper = HttpWrapper()
wrapper.silentPostData(serverurl: mdmiosagent_Constants.NATIVE_APP_SERVLET, urldata: jsonData)
} catch {
NSLog("json error")
}

最佳答案

在iOS 7及以上版本可以使用以下方法

func locationManager(manager: CLLocationManager!,didUpdateLocations locations: [AnyObject]!){
print("latitude:\(manager.location.coordinate.latitude)")
print("longitude:\(manager.location.coordinate.longitude)")
}


func locationManager(manager: CLLocationManager!,didFailWithError error: NSError!){
print("error")
}

确保一旦你的类(class)确认

 import CoreLocation

class ViewController: UIViewController , CLLocationManagerDelegate{

随叫随到

  self.locationManager = CLLocationManager()
let Device = UIDevice.currentDevice()
private let iosVersion = Double(Device.systemVersion) ?? 0
if iosVersion >= 8 {
self.locationManager.requestWhenInUseAuthorization()
}
self.locationManager.delegate = self
self.locationManager.startUpdatingLocation()

更新

添加这个并检查状态是否已经被授予

  // authorization status
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)")
}
}

关于ios - 如何使用 swift 在 iOS7 中调用 CLLocation Manager 委托(delegate)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37180228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com