This question already has answers here:
"Thread 1: stopped at breakpoint" error when initializing an NSURL object
(3 answers)
Closed 6 years ago.
I get an "lldb" error in my Debug Area when I try to run this app but I don't know why, because I didn't change anything. The screenshot up top shows what happens when the app gets automatically closed.
import UIKit
class ViewController: UIViewController {
#IBOutlet var ScoreLabel: UILabel!
var taps = 0{
didSet {
if taps == 330 {
print("You have reaches 5 taps !!")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
let defaults = NSUserDefaults.standardUserDefaults()
if let storedTaps = defaults.objectForKey("key") as? Int {
self.taps = storedTaps
setLabel(storedTaps)
}
}
#IBAction func ScoreButton(sender: UIButton) {
taps += 1
setLabel(taps)
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(taps, forKey: "key")
}
func setLabel(taps:Int) {
ScoreLabel.text = "Taps: \(taps)"
}
}
You have set a breakpoint in your code most probably unintentionally. Just hold and drag it out till you see an 'X' to remove that breakpoint or right click on it and delete/disable breakpoint.
Related
I am making my first XCode project and I want to make an app where you can click on a tableviewcell and then you can see are directed to the next detailpage where the location is on the map. The problem is that I get a thread when i run the app:
Fatal error: Unexpectedly found nil while unwrapping an Optional value
and in my output i see that (MKMapView!) nil is.
This is my code on my MapViewController (the detailpage where the map is supposed to be)
import UIKit
import MapKit
class MapViewController: UIViewController, MKMapViewDelegate{
#IBOutlet weak var mijnMap: MKMapView!
var currentDetail: Parking? {
didSet {
showInfoDetail()
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
func showInfoDetail() {
if let detail = currentDetail {
let coordinaat = CLLocationCoordinate2D(latitude: CLLocationDegrees(detail.latitude)
, longitude: CLLocationDegrees(detail.longitude))
MKMapPointForCoordinate(coordinaat)
mijnMap.centerCoordinate = coordinaat
mijnMap.region = MKCoordinateRegionMakeWithDistance(coordinaat, 1000, 1000)
let parkingAnnotation = MKPointAnnotation()
parkingAnnotation.coordinate = coordinaat
parkingAnnotation.title = detail.title
parkingAnnotation.subtitle = detail.city
mijnMap.addAnnotation(parkingAnnotation)
}
}
}
I get the threat on this line mijnMap.centerCoordinate = coordinaat
Can someone help me with this? Thanks!
The problem is that because of didSet in
var currentDetail: Parking? {
didSet {
showInfoDetail()
}
}
when you try to set currentDetail from another VC the call to method showInfoDetail triggers and this happen before the VC is presented which means prior to view loading resulting in a crash as all IBOutlets are not yet been initialized , so delay the call to it in viewDidAppear or check the map before usage
var currentDetail: Parking? {
didSet {
if mijnMap != nil {
showInfoDetail()
}
}
}
Note in second option you have at call showInfoDetail in viewDidLoad / viewDidAppear , I'm not suggesting removing didSet as you may want to change that string value in MapViewController and trigger the same function every change
This question already has answers here:
Perform Segue on ViewDidLoad
(12 answers)
Closed 4 years ago.
I`m trying to perform a segue if its the first time the app is loading.
I can see my print message in the debugger, but the Perform Segue is not working. I don't get any errors.
Can somebody please tell me whats wrong?
import UIKit
import LocalAuthentication
let isFirstLaunch = UserDefaults.isFirstLaunch()
extension UserDefaults {
// check for is first launch - only true on first invocation after app install, false on all further invocations
// Note: Store this value in AppDelegate if you have multiple places where you are checking for this flag
static func isFirstLaunch() -> Bool {
let hasBeenLaunchedBeforeFlag = "hasBeenLaunchedBeforeFlag"
let isFirstLaunch = !UserDefaults.standard.bool(forKey: hasBeenLaunchedBeforeFlag)
if (isFirstLaunch) {
UserDefaults.standard.set(true, forKey: hasBeenLaunchedBeforeFlag)
UserDefaults.standard.synchronize()
}
return isFirstLaunch
}
}
class loginVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if isFirstLaunch == false {
performSegue(withIdentifier: "setPassword", sender: self)
print("testFalse") }
else {
performSegue(withIdentifier: "setPassword", sender: self)
print("testTrue")}
// Do any additional setup after loading the view, typically from a nib.
}
You can't use performSegue() from within viewDidLoad(). Move it to viewDidAppear().
At viewDidLoad() time, the current view isn't even attached to the window yet, so it's not possible to segue yet.
You can also use a different approach - change the main window's rootViewController to the view controller of your choice depending on isFirstLaunchboolean
UIApplication.shared.keyWindow?.rootViewController = setPasswordViewController
I am trying to implement UITapGestureRecognizer, Idea is that on tap of label I will get a pop up displaying the number to make call and it should come up with pop up alert saying call or cancel!!
Code I've written worked for me in 3 to 4 places but I am stuck at one point
In this screen I have a tableview with prototype cells grouped type here, please check this Image:
Link For Image
Third Cell
Now If I am Tapping 065668982 I have canOpenURL: failed for URL: "telprompt://065668982" - error: "This app is not allowed to query for scheme telprompt" which actually works on iPhone not on simulator and it pulls to call which is working fine.
Second Cell
If I am Tapping 065454858 I have canOpenURL: failed for URL: "telprompt://065668982" - error: "This app is not allowed to query for scheme telprompt" which actually works on iPhone not on simulator and it pulls to call which is working fine.
first Cell
But for first one it never works and end up with fatal error: unexpectedly found nil while unwrapping an Optional value
NOTE : I am Getting phone Number from an API and append the data in view controller to UITableViewCell.
I Hope I make sense, Thanks in advance for any help also if I am not clear please comment below
Here is my code:
import UIKit
import Foundation
class XyzTableViewCell: UITableViewCell
{
#IBOutlet weak var phoneNumber: UILabel!
var touchContact : String = ""
var myCell: MyCellData! {
didSet {
self.updateUI()
}
}
func updateUI()
{
touchContact = vicarCell.phone_no
//Tap Gesture
tapGestureAddonView()
}
//MARK:- Tap to Call and Open Email
func tapGestureAddonView(){
let contacttap = UITapGestureRecognizer(target: self, action:("contactTapped"))
contacttap.numberOfTapsRequired = 1
phoneNumber!.userInteractionEnabled = true
phoneNumber!.addGestureRecognizer(contacttap)
}
func contactTapped() {
// do something cool here
print("contactTapped")
print(touchContact)
dispatch_async(dispatch_get_main_queue())
{
if UIApplication.sharedApplication().canOpenURL(NSURL(string: "telprompt://\(self.touchContact)")!){
UIApplication.sharedApplication().openURL(NSURL(string: "telprompt://\(self.touchContact)")!)
}
else{
//showAlert("Info",message: "Your device could not called" ,owner: self)
}
}
}
The issues: 1) you should add gesture only once 2) you should check NSURL for nil. Let me assume that you use storyboard and improve your code a bit
class XyzTableViewCell: UITableViewCell
{
#IBOutlet weak var phoneNumber: UILabel!
var touchContact : String = ""
var myCell: MyCellData! {didSet {self.updateUI()}}
func updateUI() {
touchContact = myCell.phone_no // did you mean myCell instead vicarCell?
}
override func awakeFromNib() {
super.awakeFromNib()
tapGestureAddonView()
}
func tapGestureAddonView(){
let contacttap = UITapGestureRecognizer(target: self, action: #selector(contactTapped))
contacttap.numberOfTapsRequired = 1
phoneNumber!.userInteractionEnabled = true
phoneNumber!.addGestureRecognizer(contacttap)
}
func contactTapped() {
print("contactTapped")
print(touchContact)
if touchContact.isEmpty {return}
guard let url = NSURL(string: "telprompt://\(touchContact)") else {
print("url string invalid")
return
}
dispatch_async(dispatch_get_main_queue())
{
if UIApplication.sharedApplication().canOpenURL(url){
UIApplication.sharedApplication().openURL(url)
} else{
//showAlert("Info",message: "Your device could not called" ,owner: self)
}
}
}
}
I'm trying to make an app that lets users input 4 numbers and display what cellular network is that number. Is there a way to automatically display the numbers in the label after the user inputs the numbers without clicking a button? I actually have a code that lets the user input the number but the user must click the enter button for it to display the result on the label. Is there a way for it to automatically display the result? By the way, I'm actually new to swift so I apologize. Here is the code:
import UIKit
import Firebase
class ViewController: UIViewController, FBSDKLoginButtonDelegate {
#IBOutlet weak var numField: UITextField!
#IBOutlet weak var answerField: UILabel!
#IBAction func enterButton(sender: AnyObject) {
matchNumber()
}
func matchNumber(){
let number: String = numField.text!
let numRef = Firebase(url: "https://npi2.firebaseio.com/num_details")
numRef.queryOrderedByKey().observeEventType(.ChildAdded, withBlock: { snapshot in
let network = snapshot.value as! String!
if snapshot.key == self.numField.text! {
self.answerField.text = network
}
else {
self.answerField.text = "Missing"
}
})
}
Add a target to your numField, something like this...
override func viewDidLoad() {
super.viewDidLoad()
self.numField.addTarget(self, action: "editingChanged:", forControlEvents: .EditingChanged)
}
This will trigger the editingChanged method every time a character changes in the numField.
func editingChanged(textField:UITextField) {
if let text = textField.text {
if text.characters.count == 4 {
matchNumber()
}
}
}
Finally we check if there is a string in the input and if it is 4 characters long before running the matchNumber method.
You could use the didSet method.
var numberstring = String() {
didSet {
yourlabel.text = numberstring
}
}
If you are using textfield to take input then you can use textfieldDidEndEditing delegate method.
I'm trying to follow a course on Swift by Stanford on iTunes U but I got stuck when it came to creating the enter key. As soon as I press the enter key in the simulator the app crashes and gives me no description of why. Here's the code:
import UIKit
class ViewController: UIViewController {
#IBOutlet var display: UILabel!
var userIsInTheMiddleOfTypingNumber = false
#IBAction func appendDigit(sender: UIButton) {
let digit = sender.currentTitle!
if userIsInTheMiddleOfTypingNumber == false {
display.text = digit
userIsInTheMiddleOfTypingNumber = true
} else {
display.text = display.text! + digit
}
}
var operandStack = Array<Double>()
#IBAction func enter() {
userIsInTheMiddleOfTypingNumber = false
operandStack.append(displayValue)
print("operandStack = \(operandStack)")
}
var displayValue: Double {
get {
return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
} set {
display.text = "\(newValue)"
userIsInTheMiddleOfTypingNumber = false
}
}
}
This was my first app that I worked on too! This happens to me all the time. What probably happened is you are getting a SIGABRT because the function from the button has been changed or has a bad reference. A simple way to fix this is like so:
Click on the button that is causing the program to crash in the storyboard
Go to the Show Connections Inspector (Blue arrow with a circle *See picture)
Click the black x in the Connections inspector (it should show up like this in the picture, my connection is blurEffect).
Go back to the view controller and comment out or delete the reference to the old button connections (There should be a black dot by the function to say that there is a missing connection).
Try relinking the function button back to the code and put the old code back in the function.
Hope this helps! :)