【问题标题】:Can't find location and Alert dismiss automatic in iOS在 iOS 中找不到位置和警报自动关闭
【发布时间】:2018-04-19 16:16:21
【问题描述】:
import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    @IBOutlet weak var mapKit: MKMapView!

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location = locations[0]
        let span: MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
        let myLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
        let region: MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
        mapKit.setRegion(region, animated: true)
        self.mapKit.showsUserLocation = true
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        let manager = CLLocationManager()
        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestAlwaysAuthorization()
        manager.startUpdatingLocation()
    }
}

这是我的源代码。我正在使用 Xcode 9 和 swift 4.0

当我构建并运行时,调试区域会打印此“无法从角落 4 插入法律归属”,并使用 GPS 警报自动关闭。所以我不能接受使用 GPS 允许。

我也是这样完成info.plist设置的。

隐私 - 始终定位和使用时使用说明 隐私 - 始终位置 使用说明 隐私 - 使用时的位置使用说明。

有什么问题?

【问题讨论】:

    标签: ios swift xcode mapkit cllocationmanager


    【解决方案1】:

    将 CLLocationManager 设为全局实例 var -

        @IBOutlet weak var mapKit: MKMapView!
        let manager = CLLocationManager()
    
        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
                let location = locations[0]
                let span: MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
                let myLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
                let region: MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
                mapKit.setRegion(region, animated: true)
                self.mapKit.showsUserLocation = true
            }
    
    
        override func viewDidLoad() {
            super.viewDidLoad()
            manager.delegate = self
            manager.desiredAccuracy = kCLLocationAccuracyBest
            manager.requestAlwaysAuthorization()
            manager.startUpdatingLocation()
        }
    

    这将防止警报自动关闭。

    【讨论】:

    • 有什么区别?在 viewDidLoad 中声明
    • @usinuniverse,在 viewDidLoad 中它的范围是直到那个函数。一旦功能完成,该属性将被释放。如果财产是释放,这意味着现在没有人是所有者来处理代表。如果您在全局范围内声明,您的实例将一直有效,直到类上线为止。
    • @RishiChaurasia,非常感谢。我明白了。
    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-01
    • 2014-05-30
    • 2014-12-12
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    相关资源
    最近更新 更多