在搜索栏点击时崩溃

8

当在UIViewController中点击搜索栏文本字段时,应用程序崩溃。

我的视图控制器如下所示 -

class DetailViewController: UIViewController, GMSMapViewDelegate, UISearchBarDelegate {

let testBaseUrl = "https://maps.googleapis.com/maps/api/geocode/json?"

var searchBar = UISearchBar()
var searchImageView   : UIImageView!
var mapView: GMSMapView!
var markers = [GMSMarker]()
var cameraPosition: GMSCameraPosition!
var searchAddress: String!

var mapButton = UIBarButtonItem()
var listButton = UIBarButtonItem()
var filterButton = UIBarButtonItem()
var arrayOfButtons = [AnyObject]()

override func viewDidLoad() {
    super.viewDidLoad()

    cameraPosition = GMSCameraPosition.cameraWithLatitude(-37.809487,
        longitude:144.965699, zoom:17.5, bearing:30, viewingAngle:40)
    mapView = GMSMapView.mapWithFrame(CGRectZero, camera:cameraPosition)

    mapView.delegate = self
    self.view = mapView

}

override func viewWillAppear(animated: Bool) {
    setUISearchView()

}

//MARK: SearchBar Methods

func setUISearchView(){

    let searchImage = UIImage(named: "search")!

    searchImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: searchImage.size.width, height: searchImage.size.height))
    searchImageView.image = searchImage

    let rightGestureRecognizer:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "showSearchBar")
    searchImageView.addGestureRecognizer(rightGestureRecognizer)

    navigationItem.rightBarButtonItem?.customView = searchImageView

}

func setUICancelView(){

    let searchImage = UIImage(named: "cancel")!

    searchImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: searchImage.size.width, height: searchImage.size.height))
    searchImageView.image = searchImage

    let rightGestureRecognizer:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "hideSearchBar")
    searchImageView.addGestureRecognizer(rightGestureRecognizer)

    navigationItem.rightBarButtonItem?.customView = searchImageView

}


func searchButtonPressed(sender: UIBarButtonItem) {
    showSearchBar()
}

func showSearchBar() {

    searchBar.delegate = self
    searchBar.searchBarStyle = UISearchBarStyle.Minimal

    let textFieldInsideSearchBar = searchBar.valueForKey("searchField") as? UITextField

    textFieldInsideSearchBar?.textColor = UIColor.whiteColor()

    UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).tintColor = UIColor.redColor()

    searchBar.alpha = 0
    navigationItem.titleView = searchBar

    UIView.animateWithDuration(0.5, animations: {
        self.searchBar.alpha = 1
        self.setUICancelView()
        }, completion: { finished in
            self.searchBar.becomeFirstResponder()
    })
}

func hideSearchBar() {
    setSearchBarTitle(searchAddress!)

    searchImageView.alpha = 0


    UIView.animateWithDuration(0.3, animations: {

        self.searchBar.hidden =  false
        self.searchBar.alpha = 0
        self.setUISearchView()
        }, completion: { finished in
            self.searchBar.resignFirstResponder()

    })
}

//MARK: UISearchBarDelegate
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
     print("search is working ")
}

func searchBarCancelButtonClicked(searchBar: UISearchBar) {
    print("searchBarCancelButtonClicked!")
    hideSearchBar()
}

func searchBarSearchButtonClicked(searchBar: UISearchBar) {

    hideSearchBar()

     // Do something..
}

func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
    print("searchBarTextDidBeginEditing!")
}  

func setSearchBarTitle(streetAddress: NSString){
    //Adding Title Label
    let navigationTitlelabel = UILabel(frame: CGRectMake(0, 0, 200, 21))
    navigationTitlelabel.center = CGPointMake(160, 284)
    navigationTitlelabel.textAlignment = NSTextAlignment.Center
    navigationTitlelabel.textColor  = UIColor.whiteColor()
    navigationTitlelabel.text = "streetAddress" as! String
    self.navigationController!.navigationBar.topItem!.titleView = navigationTitlelabel
}

func setSearchBar(){

    // Remove the drop shadow from the navigation bar for distinct status bar
    navigationController!.navigationBar.clipsToBounds = true

    navigationController!.navigationBar.barTintColor = UIColor.candyGreen()
}


//MARK: Other logic

我的场景看起来像这样 - enter image description here

当点击搜索栏编辑文本字段时,应用程序会在设备上崩溃。不过,如果我在showSearcBar()中注释掉self.searchBar.becomeFirstResponder(),结果没有输入键,它可以正常工作。同样的代码在模拟器上可以正常工作,因为我可以使用我的开发机密钥来进入搜索栏字段。

我是一个新手,在Swift开发方面没有前面的Obj C知识。

  • 所有UI控件都会消失,只剩下Google地图,当我点击搜索栏编辑区域*时

编辑

崩溃日志:

Jan 10 23:33:33 Atul-Kaushiks-iPhone SpringBoard[54] <Notice>: CoreLocation: CLPocketStateService 43328.265701: Stationary,1,Orientation,2,Proximity,0,State,1
Jan 10 23:33:35 Atul-Kaushiks-iPhone SpringBoard[54] <Notice>: CoreLocation: CLPocketStateService 43329.719682: Stationary,2,Orientation,2,Proximity,0,State,2
Jan 10 23:33:39 Atul-Kaushiks-iPhone SpringBoard[54] <Notice>: CoreLocation: CLPocketStateService 43333.481776: Stationary,1,Orientation,2,Proximity,0,State,1
Jan 10 23:33:39 Atul-Kaushiks-iPhone SpringBoard[54] <Notice>: CoreLocation: CLPocketStateService 43333.757166: Stationary,1,Orientation,1,Proximity,0,State,3
Jan 10 23:33:41 Atul-Kaushiks-iPhone SpringBoard[54] <Warning>: LICreateIconForImage passed NULL CGImageRef image
Jan 10 23:33:41 Atul-Kaushiks-iPhone SpringBoard[54] <Notice>: CoreLocation: CLPocketStateService 43336.076814: Stationary,1,Orientation,2,Proximity,0,State,1
Jan 10 23:33:42 Atul-Kaushiks-iPhone SpringBoard[54] <Warning>: HW kbd: Failed to set (null) as keyboard focus
Jan 10 23:33:42 Atul-Kaushiks-iPhone SpringBoard[54] <Notice>: CoreLocation: CLPocketStateService 43336.927797: Stationary,2,Orientation,2,Proximity,0,State,2
Jan 10 23:33:50 Atul-Kaushiks-iPhone SpringBoard[54] <Warning>: [MPUSystemMediaControls] Disabling lock screen media controls updates for screen turning off.
Jan 10 23:33:50 Atul-Kaushiks-iPhone backboardd[56] <Notice>: [HID] [MT] MTSimpleHIDManager::setPropertyInternal detection mode: 3->255 
Jan 10 23:33:50 Atul-Kaushiks-iPhone kernel[0] <Notice>: AppleKeyStore: operation failed (pid: 54 sel: 26 ret: e00002e2 '-536870174')
Jan 10 23:33:50 Atul-Kaushiks-iPhone UserEventAgent[23] <Error>:  LockStateNotifier aksNotificationCallback posting notification: com.apple.mobile.keybagd.lock_status
Jan 10 23:33:50 Atul-Kaushiks-iPhone UserEventAgent[23] <Notice>: (Note ) PIH: Lock status changed.
Jan 10 23:33:51 Atul-Kaushiks-iPhone MobileMail[165] <Warning>: Key bag transitioning from unlocked to locking
Jan 10 23:33:51 Atul-Kaushiks-iPhone UserEventAgent[23] <Warning>: [autosu error]: SPI for AutoSU: unable to find bestSuStart or bestSuEnd with corresponding prob above desired threshold
Jan 10 23:33:51 Atul-Kaushiks-iPhone com.apple.CDScheduler[23] <Error>: AutoSu doesn't have any prediction yet
Jan 10 23:33:51 Atul-Kaushiks-iPhone com.apple.CDScheduler[23] <Error>: Failed to get device restart forecast
Jan 10 23:33:51 Atul-Kaushiks-iPhone SpringBoard[54] <Warning>: [MPUSystemMediaControls] Updating supported commands for now playing application.
Jan 10 23:33:51 Atul-Kaushiks-iPhone wirelessproxd[55] <Notice>: (Error) updateScanner - central is not powered on: 4
Jan 10 23:34:00 Atul-Kaushiks-iPhone kernel[0] <Notice>: AppleKeyStore:Sending lock change 1 for handle 0
Jan 10 23:34:00 Atul-Kaushiks-iPhone UserEventAgent[23] <Error>:  LockStateNotifier aksNotificationCallback posting notification: com.apple.mobile.keybagd.lock_status
Jan 10 23:34:00 Atul-Kaushiks-iPhone UserEventAgent[23] <Notice>: (Note ) PIH: Lock status changed.
Jan 10 23:34:00 Atul-Kaushiks-iPhone MobileMail[165] <Warning>: Key bag transitioning from locking to locked
Jan 10 23:34:13 Atul-Kaushiks-iPhone syncdefaultsd[815] <Notice>: (Note ) marked "com.me.keyvalueservice" topic as "enabled" on <APSConnection: 0x12ee0b070>

添加异常断点。在崩溃时查看哪些内容被命中。还可以使用断点进行逐步调试。 - Teja Nandamuri
尝试使用NSLog打印searchImageView的框架,看看是否会输出内容。 - Teja Nandamuri
我们在谈论维度吗?我正在为searchImageView获取有效的dims。由于我没有Objective-C方面的经验,请告诉我这里是否有误。 - Atul Kaushik
请问您能否附上崩溃报告? - fredpi
之前遇到过类似的问题。我的问题是我搜索的内容还没有完全加载。在启用搜索栏之前,请确认您的内容是否全部加载完成。 - joels
显示剩余3条评论
3个回答

2

崩溃截图

屏幕截图

我尝试使用你的代码,当我点击取消时,应用程序会崩溃,我发现searchAddress是nil,但是你使用了'setSearchBarTitle(searchAddress!)',所以崩溃了。

我建议将searchAddress设置为可选值,这样就没有问题了。


2

变量searchAddress被声明为隐式解包可选项。

当搜索栏按钮被点击时,调用方法hideSearchBar()并解包searchAddress。这会导致崩溃,因为searchAddressnil

解决方案:将searchAddress声明为非可选项,并用空字符串初始化。

var searchAddress = ""

并去掉感叹号

setSearchBarTitle(searchAddress)

谢谢@vadian,但我仍然遇到了崩溃。它发生在软键盘出现一小段时间后立即发生。此外,如果这是原因,那么它不应该在模拟器上工作。 - Atul Kaushik
设置一个异常断点,并在异常被触发时检查 searchImageView 是否为 nil - vadian
@vadian的回答是正确的。你一定是从其他地方得到了崩溃。 - Ducky
@Ducky,我已经添加了崩溃日志。我尝试了Vadian的解决方案,但没有帮助。由于我的知识有限,我正在苦苦挣扎。当我点击搜索栏编辑字段时,所有UI控件都会消失,只剩下谷歌地图。 - Atul Kaushik
请分享你的 GitHub 仓库。 - Ducky

1
我尝试了您的代码,去掉了Google Maps视图,没有遇到任何崩溃问题。也许Google地图视图和UISearchField存在问题,请尝试通过排除self.view = mapView暂时删除Google地图视图,并在下面的评论部分反馈是否有效。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接