2017-09-16 45 views
0

我試圖在地圖視圖中顯示用戶當前的位置,但我的位置管理器功能從'CLLocation?'下載?到'CLLocation'只解開可選項;你的意思是使用'!'嗎?

這裏的第一線得到一個錯誤是我的代碼

import UIKit 
import MapKit 

class FirstViewController: UIViewController, CLLocationManagerDelegate { 

@IBOutlet weak var mapkitView: MKMapView! 
var locationManager: CLLocationManager! 

override func viewDidLoad() 
{ 
    super.viewDidLoad() 

    if (CLLocationManager.locationServicesEnabled()) 
    { 
     locationManager = CLLocationManager() 
     locationManager.delegate = self 
     locationManager.desiredAccuracy = kCLLocationAccuracyBest 
     locationManager.requestAlwaysAuthorization() 
     locationManager.startUpdatingLocation() 
    } 
} 

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) 
{ 
    let location = locations.last as! CLLocation 

    let center = CLLocationCoordinate2DMake(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude) 

    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)) 

    self.mapkitView.setRegion(region, animated: true) 
} 
} 

錯誤我'越來越是'從'CLLocation'降級了嗎?'以「CLLocation」只有解開自選;「!」嗎?你的意思是使用

上線讓位置= locations.last作爲CLLocation

我纔開始迅速的今天,所以請裸跟我 任何幫助!讚賞

+0

你不需要'作爲!因爲數組包含'CLLocation',所以你可以說'locations.last!'但請不要。使用條件解包'如果讓位置= locations.last {'。但是,如果您閱讀了「MKMapView」的文檔,您會發現如果啓用用戶跟蹤模式,它可以爲您完成所有這些工作。 – Paulw11

+0

謝謝我現在沒有收到任何錯誤,但是當它運行時,它只顯示沒有我的位置的地圖,爲什麼? – Will

+0

您是否被提示允許位置訪問?您是在模擬器還是真實設備上測試?如果模擬器,你是否從菜單模擬了一個位置?如果一個真實的設備,它有一個位置修復? – Paulw11

回答

0

您是力鑄造OptionalCLLocationCLLocation,這就是爲什麼斯威夫特建議簡單地強制解開它:

let location = locations.last! 

這個版本(和你)無線如果locations爲空,則會崩潰。

因此,我建議從來沒有強迫任何東西展開,並使用guard代替:

guard let location = locations.last else { 
    return 
} 
+0

謝謝我現在沒有得到任何錯誤,但是當它運行時,它只顯示沒有我的位置的地圖,爲什麼? – Will

+0

這是另一個話題。按照@ Paulw11的建議(啓用用戶跟蹤模式)和/或發佈另一個問題。 – shallowThought