簡體   English   中英

在嘗試查找用戶位置“由於未捕獲的異常'NSRangeException'而終止應用程序”時,Swift有時會給出此AppDelegate錯誤。

[英]Swift sometimes give this AppDelegate Error when try to find user location “Terminating app due to uncaught exception 'NSRangeException'..”

在嘗試查找用戶位置時,Swift有時會出現此AppDelegate錯誤

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray'
*** First throw call stack:
(0x18b3fd1b8 0x189e3455c 0x18b367bac 0x1000ffd20 0x1000fe7f4 0x1000fea30 0x193400a38 0x1934002b4 0x1933f34b8 0x18b3aaa44 0x18b3aa240 0x18b3a8538 0x18b2d62b8 0x18cd8a198 0x19131d7fc 0x191318534 0x100108078 0x18a2b95b8)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

這是我的locationManager函數:

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

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations.last        
    myLat = (location?.coordinate.latitude)!
    myLng = (location?.coordinate.longitude)!        
    self.locationManager.stopUpdatingLocation()
    createMarker(lat: myLat,lng: myLng,zoom: 16)        
}

有時它運行良好,但有時應用程序崩潰並出現此AppDelegate錯誤。 那么,為什么會出現此錯誤以及如何解決?

您假設[CLLocation]數組實際上具有元素,但並不總是如此。 添加if let根據是否提供位置來有條件地處理該位置。

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.last {
        myLat = location.coordinate.latitude
        myLng = location.coordinate.longitude
        self.locationManager.stopUpdatingLocation()
        createMarker(lat: myLat, lng: myLng, zoom: 16) 
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM