Reputation: 5201
App crashes when search bar text field is tapped in UIViewController
My ViewController looks like this -
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
}
App crashes on device when search bar edit text field is tapped. Though, it works fine if I comment self.searchBar.becomeFirstResponder() in showSearcBar() resulting in no key for input. Same code works fine on simulator as I can use my development machine keys to enter search bar field.
I'm new to swift development with no previous knowledge of Obj C.
EDIT
Crash Log :
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>
Upvotes: 9
Views: 2603
Reputation: 113
Crash Screen Shot
I try to use you code, when i tap cancel , the app crash and i found the searchAddress is nil, but you 'setSearchBarTitle(searchAddress!)', so crash.
I suggest set the searchAddress is optional value, that is ok.
Upvotes: 3
Reputation: 8942
I tried your code by myself while removing the Google Maps view, and didn't run into any crashes.
Maybe there is an issue with Google maps view and UISearchField, so please try to temporarily remove the Google maps views by excluding self.view = mapView
, and give feedback whether it works using the comment section below.
Upvotes: 1
Reputation: 285150
The variable searchAddress
is declared as implicit unwrapped optional.
When the search bar button is clicked the method hideSearchBar()
is called and searchAddress
is unwrapped. That causes the crash because searchAddress
is nil
.
Solution: Declare searchAddress
as non optional and initialize it with an empty string.
var searchAddress = ""
and remove the exclamation mark
setSearchBarTitle(searchAddress)
Upvotes: 2