首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Swift:"mapView.showUserLocation = true“返回”致命错误:在展开可选值(lldb)时意外发现nil“

Swift:"mapView.showUserLocation = true“返回”致命错误:在展开可选值(lldb)时意外发现nil“
EN

Stack Overflow用户
提问于 2015-02-25 06:56:11
回答 2查看 1.6K关注 0票数 1

所以我试着在Swift中使用像"bar“或"pizza”这样的关键词来搜索当地的商家。我将搜索链接到按钮操作,以便在地图上定义的区域内弹出位置。然而,我甚至不能让应用程序加载用户位置,因为我得到了一个零错误。

这是我的AppDelegate:

代码语言:javascript
复制
import UIKit
import CoreLocation

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
var locationManager: CLLocationManager?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    locationManager = CLLocationManager()
    locationManager?.requestWhenInUseAuthorization()
    return true
}

func applicationWillResignActive(application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

func applicationDidEnterBackground(application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(application: UIApplication) {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


}

下面是我的ViewController.swift:

代码语言:javascript
复制
import Foundation
import UIKit
import MapKit

class ViewController: UIViewController, MKMapViewDelegate {

@IBOutlet weak var mapView: MKMapView!

@IBAction func searchBars(sender: AnyObject) {
    let request = MKLocalSearchRequest()
    request.naturalLanguageQuery = "Bar"
    request.region = mapView.region

    let search = MKLocalSearch(request: request)
    search.startWithCompletionHandler({(response: MKLocalSearchResponse!, error: NSError!) in

        if error != nil {
            println("Error occurred in search: \(error.localizedDescription)")
        } else if response.mapItems.count == 0 {
            println("No matches found")

            for item in response.mapItems as [MKMapItem] {
                println("Name = \(item.name)")
                println("Phone = \(item.phoneNumber)")
            }
        }
        })

}

func mapView(mapView: MKMapView!, didUpdateUserLocation userLocation: MKUserLocation!) {
    mapView.centerCoordinate = userLocation.location.coordinate
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    mapView.showsUserLocation = true
    mapView.delegate = self
}

@IBAction func zoomIn(sender: AnyObject) {
    let userLocation = mapView.userLocation

    let region = MKCoordinateRegionMakeWithDistance(userLocation.location.coordinate, 2000, 2000)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

返回nil错误的行在我的ViewController.swift文件中的@IBAction func zoomIn下,该行为: let region =nil 2000,2000)。由于某种原因,这会给出一个nil值。

EN

回答 2

Stack Overflow用户

发布于 2015-02-25 08:05:43

您对这一行所做的是创建一个尚未实例化的mapView对象。

代码语言:javascript
复制
weak var mapView: MKMapView!

出现这个错误是因为您试图将showsUserLocation属性更改为一个尚不存在的对象,它是空的。

如果你在故事板中创建了地图,你需要做的是删除弱的变量线,并放置一个IBOutlet (按住Ctrl键并从故事板中单击并拖动)。

票数 1
EN

Stack Overflow用户

发布于 2015-02-26 05:29:38

非常感谢Skoua的帮助。在他帮助我使用IBOutlet后,我自己找出了问题所在。

这是修正后的代码。

代码语言:javascript
复制
@IBAction func searchBars(sender: AnyObject) {
    matchingItems.removeAll()
    let request = MKLocalSearchRequest()
    request.naturalLanguageQuery = "bar"
    request.region = mapView.region

    let search = MKLocalSearch(request: request)
    search.startWithCompletionHandler({(response: MKLocalSearchResponse!, error: NSError!) in

        if error != nil {
            println("Error occurred in search: \(error.localizedDescription)")
        } else if response.mapItems.count == 0 {
            println("No matches found")
//This is where the problem occured
        } else {
            println("Matches found")
        //I needed to insert an else statement for matches being found
            for item in response.mapItems as [MKMapItem] {
                //This prints the 'matches' into [MKMapItem]
                println("Name = \(item.name)")
                println("Phone = \(item.phoneNumber)")

                self.matchingItems.append(item as MKMapItem)
                println("Matching items = \(self.matchingItems.count)")

                var annotation = MKPointAnnotation()
                annotation.coordinate = item.placemark.coordinate
                annotation.title = item.name
                self.mapView.addAnnotation(annotation)
            }
        }
        })

}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28707991

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档