Swift SIGABRT Error? But I resolved it? [closed] - swift

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have yet another error, its the common swift error
Thread 1: signal SIGABRT
I know how to fix this error. Here is my recent question.
Can't resolve error: Thread 1: signal SIGABRT in swift XCODE
But now I am making a new project, and I got this error! So I tried to fix it, I thought I got it - but I didn't.. I have checked all my outlets and everything, But there is no trace of where this is coming from...
Here is my code:
import UIKit
class ViewController: UIViewController {
//Variables
var tempature:Int = 50
var battery:Int = 100
var monsterCount:Int = 0
//Outlets
#IBOutlet weak var BatteryLevel: UILabel!
#IBOutlet weak var TempDisplay: UILabel!
//The spy camera
#IBOutlet weak var monsterImageDisplay: UIImageView?
//The background image
#IBOutlet weak var backgroundImageShow: UIImageView!
//Functions
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
monsterImageDisplay?.isHidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//The interval to keep things going
var helloWorldTimer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: Selector(("spawnMonstor")), userInfo: nil, repeats: true)
func spawnMonstor() {
monsterImageDisplay?.isHidden = false
monsterCount += 1
if monsterCount >= 3 {
let randomNumberBackgroundImage = arc4random_uniform(10)
if randomNumberBackgroundImage >= 5 {
backgroundImageShow.image = UIImage(named: "main-room-jumpTop")
} else if randomNumberBackgroundImage <= 5 {
backgroundImageShow.image = UIImage(named: "main-room-jumpBottom")
}
} else if monsterCount >= 5 {
let alert = UIAlertController(title: "GAME OVER", message: "Sorry! You died...", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Okay..", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
//The shock rooms button
#IBAction func ShockRooms(_ sender: Any) { monsterImageDisplay?.isHidden = true
}
}

Check that your UIImage names are the EXACT same names as the ones in your xcassets folder.
Instead of using the helloWorldTimer, write this at the top of your class, underneath your outlets:
var helloWorldTimer = Timer()
And then inside of your viewDidLoad, add:
helloWorldTimer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: Selector(("spawnMonstor")), userInfo: nil, repeats: true)

Related

I am not sure why I keep getting the error Value of type '(AnyObject) -> ()' has no member 'currentTitle'

#IBAction func Hint(_ sender: UIButton) {
if Action.currentTitle != Int(rightAnswerPlacement) // this is the line where I keep getting error I posted above
{
Action.isHidden = true // true to hide the button
}
}
#IBOutlet weak var Hint: UIButton!
//Label for qs
#IBOutlet weak var label: UILabel!
//button for choices
#IBOutlet weak var Action: UIButton!
#IBAction func Action(_ sender: AnyObject)
{
if (sender.tag == Int(rightAnswerPlacement))
{
print("Right")
}
else
{
print("Wrong")
let alert = UIAlertController(title: "That is incorrect", message: "Try again!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: nil))
present(alert, animated: true)
currentQuestion -= 1
//how to record which wrong answer the user is pressing
//let WrongAnswer = sender.tag.titleLabel?.text
}
This is a code for a basic quiz app on Xcode, what I am trying to do with my first few lines of code is trying to make an option disappear once I click another button
Reason for the error is that both your button and a function are named Action. In the line that gives you error, compiler thinks you are referring to the function (which is of type (AnyObject) -> ()) instead of the button. Rename either your function, or your button.
By the way, there are couple of things you should improve in your code:
by convention, names of types are uppercased, while names of instances should be lowercased
use more descriptive names for your variables and functions - i.e. hintButton instead of Hint, actionButton instead of Action for UIButton and actionButtonTapped for func

Swift 3 UIButton multiple events not detected within a less than 16 millisecond window

This is my first question on StackOverflow. I am trying to measure reaction time to stimuli and need multiple players and UIButtons for the players. The problem is if the two players in the code example are within 16 millisecond or less of each other both UIButton events come together and therefore the same time. I just did this in Android and had no problem.
I did try override of the touches_began() and the same problem. It seems as if the two UIButtons are being handled in the same interrupt as if they were a multi-touch which I have turned off for the two buttons.
I know the example is dumb but it does illustrate the 16 millisecond
issue. Just tap a bunch of times and see how many ties occur. I looked at the results of testing and I got an approximate 16 millisecond issue.
import UIKit
class ViewController: UIViewController {
weak var timer: Timer?
var startTime: Double = 0
var time: Double = 0
#IBOutlet weak var timeValueLabel1: UILabel!
#IBOutlet weak var timeValueLabel: UILabel!
#IBAction func stop1Button() {
let timeString = String(format: "%.3f", time)
timeValueLabel1.text = timeString
}
#IBAction func stopButton() {
let timeString = String(format: "%.3f", time)
timeValueLabel.text = timeString
}
override func viewDidAppear(_ animated: Bool) {
startTime = Date().timeIntervalSinceReferenceDate
timer = Timer.scheduledTimer(timeInterval: 0.001,
target: self,
selector: #selector(advanceTimer(timer:)),
userInfo: nil,
repeats: true)
}
override func viewWillDisappear(_ animated: Bool) {
timer?.invalidate()
}
func advanceTimer(timer: Timer) {
time = Date().timeIntervalSinceReferenceDate - startTime
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

How to use custom UIAlertview in multiple ViewControllers?

I am looking for a way to call a custom alert view from multiple view controllers. So far I have made several different attempts without success.
I created an alert view with an interface builder that works fine on one view controller but not the other.
I then tried creating the alert view programmatically thinking it may have something to do with the outlets not being connected on the other view controller. This one also worked on one view controller and not the other.
I made a separate swift file and made a public function and the same result. With this last method, I am able to successfully re-use a regular UIAlertController on multiple view controllers but that is not exactly what I am looking for.
With the first two methods, I do not get any compiling errors. The app runs fine and then crashes when I call the alert from another view controller.
Thanks in advance for any input!
EDIT:
This example works when I put it in another swift file.
public func showSimpleAlert(title: String, message: String?, presentingController: UIViewController) {
if IS_OS_8_OR_LATER() {
let controller = UIAlertController(title: title, message: message, preferredStyle: .Alert)
controller.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: { (action) -> Void in
}))
presentingController.presentViewController(controller, animated: true, completion: nil)
} else {
let alert = UIAlertView(title: title, message: message, delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
}
This is the one I want to work on.
public func showAlert(oMsg: String, oTitle:String) {
alertView.backgroundColor = UIColor.whiteColor()
alertView.layer.cornerRadius = 25
alertTitleLabel.text = oTitle as String
alertTitleLabel.font = UIFont(name: "Open-Sans-Bold", size: 20)
alertTitleLabel.textColor = UIColor.blackColor()
alertTitleLabel.textAlignment = .Center
alertTitleLabel.numberOfLines = 1
alertTitleLabel.frame = CGRectMake(25, 60, 264, 112)
alertLabel.text = oMsg as String
alertLabel.font = UIFont(name: "Open-Sans", size: 20)
alertLabel.textColor = UIColor.blackColor()
alertLabel.textAlignment = .Center
alertLabel.numberOfLines = 4
alertLabel.frame = CGRectMake(25, 130, 264, 112)
okButton.setTitle("OK", forState: .Normal)
okButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
okButton.frame = CGRectMake(60, 230, 197, 75)
okButton.addTarget(UIViewController.self, action:#selector(LoginViewController.buttonAction(_:)), forControlEvents: .TouchUpInside)
}
I will give the answer for a simple custom alertview which is basically a modified uiviewcontroller. you can use a uiviewcontroller as a uialertviewcontroller as follow.
Simple AlertView::
The AlertVC:
import UIKit
class ErrorAlert: UIViewController {
var titlenote:String = ""
var message:String = ""
#IBOutlet weak var cancelBtn: UIButton!
#IBOutlet weak var messageHolder: UILabel!
#IBOutlet weak var imageHolder: UIImageView!
#IBOutlet weak var titleHolder: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.black.withAlphaComponent(0.7)
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.messageHolder.text = self.message
self.titleHolder.text = self.titlenote
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func dismiss(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
}
This viewcontroller can be reuse in any vc and any number of times.
Useage Example::
let alertController = self.storyboard?.instantiateViewController(withIdentifier: "erroralert") as! ErrorAlert
alertController.titlenote = "Invalid login"
alertController.message = "Invalid facebook account."
alertController.providesPresentationContextTransitionStyle = true
alertController.definesPresentationContext = true
alertController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
alertController.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
self.present(alertController, animated: true, completion: nil)
I have made the background of the alertviewvc semitransparent by setting the alpha value.
Actual Display ::
You can make more complex alertview by this method but for reusability you have apply some logic as the button actions will be different for different viewcontroller. Example -- Sometime you can use the alertview for logout alert or sometime for submitting a form .So in both cases the action will be different so for reusability you have to write extra logic.
Another alertView::
I hope my answer will help you.:)

flip card causes fatal error in swift

I am following this card flipping tutorial and instead of creating the UIView and the UIImageViews programmatically I have created these in my storyboard.
When I click the card, the animation kicks in and turns over to the front image, but when I click again, this creates a fatal error:
unexpectedly found nil while unwrapping an Optional value.
I can not figure out why this error occurs.
Here is the code which is the transformation of the above mentioned tutorial:
class FirstViewController: UIViewController {
#IBOutlet weak var flashCardView: UIView!
#IBOutlet weak var backImage: UIImageView!
#IBOutlet weak var frontImage: UIImageView!
var showingBack = true
override func viewDidLoad() {
super.viewDidLoad()
let singleTap = UITapGestureRecognizer(target: self, action: Selector("tapped"))
singleTap.numberOfTapsRequired = 1
flashCardView.addGestureRecognizer(singleTap)
flashCardView.addSubview(backImage)
view.addSubview(flashCardView)
}
func tapped() {
if (showingBack) {
UIView.transitionFromView(backImage, toView: frontImage, duration: 1, options: UIViewAnimationOptions.TransitionFlipFromRight, completion: nil)
showingBack = false
} else {
UIView.transitionFromView(frontImage, toView: backImage, duration: 1, options: UIViewAnimationOptions.TransitionFlipFromLeft, completion: nil)
//here I get the error when flipping the card back to the back image
showingBack = true
}
}
}
I believe that when you transition, the old image's reference count is decremented, and since they're declared as weak it is getting destroyed. Try removing the weak declarations, and it will probably work. Looking at the tutorial, they don't have weak.

Swift Signal SIGABRT error while making countdown timer?

I am working on a countdown timer for my app that starts counting down from 15. This is my code:
//
import UIKit
class ViewController2: UIViewController {
#IBOutlet weak var Timer: UILabel!
var countd = 15
//
//
override func viewDidLoad() {
super.viewDidLoad()
let time = NSTimer(timeInterval: 1.0, target: self, selector: "updateCounter", userInfo: nil, repeats: true)
Timer.text = String(countd)
NSRunLoop.mainRunLoop().addTimer(time, forMode: NSDefaultRunLoopMode)
}
func updateCounter(timer: NSTimer) {
Timer.text = String(countd)
if (countd > 0){
Timer.text = String(countd--)
Timer.text = String(countd)
}
}
// Do any additional setup after loading the view.
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
However, when I run it, as soon as I get to the part with the timer I see the label flash 15 for a second but then it immediately crashes with the SIGABRT error. What can I do?
Change
selector: "updateCounter"
to
selector: "updateCounter:"
Please note that in Swift 2.2 it will become difficult to make this mistake (the compiler will warn), and in Swift 3 it will become impossible (string literal selector syntax will become illegal). You might want to update to Swift 2.2 now if you don't understand string literal selector syntax.