Ios 斯威夫特:“我的名字叫什么?”;mapView.showUserLocation=true";“返回”;致命错误:在展开可选值(lldb)时意外发现nil;

Ios 斯威夫特:“我的名字叫什么?”;mapView.showUserLocation=true";“返回”;致命错误:在展开可选值(lldb)时意外发现nil;,ios,swift,mapkit,Ios,Swift,Mapkit,所以我试图用“酒吧”或“比萨饼”等关键词在Swift中搜索当地企业。我将搜索链接到一个按钮操作,这样位置就会在地图上的一个定义区域内弹出。但是,我甚至不能让应用程序加载用户位置,因为我得到了一个零错误 这是我的AppDelegate: import UIKit import CoreLocation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow?

所以我试图用“酒吧”或“比萨饼”等关键词在Swift中搜索当地企业。我将搜索链接到一个按钮操作,这样位置就会在地图上的一个定义区域内弹出。但是,我甚至不能让应用程序加载用户位置,因为我得到了一个零错误

这是我的AppDelegate:

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:

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错误的行位于@IBAction func zoomIn下的my ViewController.swift文件中,行为:let region=mkcoordinaeregionmakewithdistance(userLocation.location.coordination,2000,2000)。由于某种原因,它给出了一个nil值

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

weak var mapView: MKMapView!
出现错误是因为您试图将
showsUserLocation
属性更改为一个尚不存在的对象,该对象为零


如果您在故事板中创建了地图,您需要做的是删除弱var行并放置一个
IBOutlet
(Ctrl+单击并从故事板拖动)。

非常感谢Skoua的帮助。在他帮我解决问题后,我自己发现了问题所在

这是正确的代码

@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)
            }
        }
        })

}

您没有分配
弱var mapView:MKMapView。如果你想让它连接到插座,你可能没有这样做。所以我必须把它连接到插座?我很难理解你的答案。好吧,这样就排除了错误。但现在我得到了另一个零值。我觉得techotopia代码解释得很糟糕。我的下一个nil值位于:@IBAction func zoomIn(发送方:AnyObject){let userLocation=mapView.userLocation let region=mkcoordinaeregionmakewithdistance(userLocation.location.coordinate,20002000)mapView.setRegion(region,动画:true)}是的。科技眼是垃圾。你能更新你的代码和你得到的新错误吗?代码被更新了!好的,所以我想我必须->玩我的应用->回到XCode->调试->模拟位置->选择一个位置。然后它会显示位置点。这样问题就解决了。但是(我讨厌回车保存注释…)我的缩放按钮不起作用,当我点击按钮搜索附近的位置时,它不会显示任何结果。最终,我的目标是根本不显示搜索结果,只将其中的5个存储到一个表中。然而,现在我想确保我已经掌握了MapKit的基础知识,我显然不知道。好吧,我更新了代码。尝试将区域设置为“放大”时出错。