Swift3.0 I want to get object of AppDelegate - ios

I wanna get object of AppDelegate.
This program can build but it will stop running with lldb error.
Maybe the problem is the dirrerence of Swift2.0 and 3.0.
My textbook is for swift2.0 but I am using xcode8.0 and Swift3.0.
Error is here.
let ap = UIApplication.shared.delegate as! AppDelegate
I used this page for fixing.
How do I get a reference to the app delegate in Swift?
import UIKit
class FirstViewController: UIViewController {
#IBOutlet weak var dataTextField: UITextField!
let ap = UIApplication.shared.delegate as! AppDelegate
override func viewWillAppear(_ animated: Bool) {
dataTextField.text = String(ap.cmValue)
}
#IBAction func tapInpu() {
dataTextField.resignFirstResponder()
if let text = dataTextField.text{
if let cmValue = Double(text){
ap.cmValue = cmValue
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

If you remove ap initialization and ap.cmValue = cmValue, does it works ?
If it does work check your outlet referencing in your storyboard you may have old non existent references

Related

self.tabBarController!.viewControllers returning nil

I have a TabBarController with four different UIViews connected to it. The TabBarController is managed from the Controller.swift file, which looks like that
import UIKit
import Firebase
class Controller: UITabBarController {
var firebaseUser = String()
override func viewDidLoad() {
super.viewDidLoad()
//let allVC = self.tabBarController?.viewControllers
//let SearchVC = allVC![1] as! SearchVC
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
However, the lines that are commented out lead to the error "...found nil while unwrapping optional.." (already getting allVC leads to the error)
How can I fix that error?
Use let allVC = self.viewControllers instead as your class is a UITabBarViewController subclass

Cannot unwrap optional value to label

I am new to this board. Please, excuse my bad english in advance.
I am trying to send a string from a subview to his parent view. If I try to set that string to a label, my app crashes with the message "unexpectedly found nil while unwrapping an Optional value".
Example code from the subview:
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.blueColor()
sendDataToVc("test")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func sendDataToVc(myString : String) {
let Vc = ViewController()
Vc.dataFromContainer(myString)
}
Example from the parent view:
class ViewController: UIViewController {
#IBOutlet weak var label1: UILabel!
var cacheStr1 : String!
var cacheStr2 : String?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
label1.text = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func dataFromContainer(containerData : String){
label1.text = cacheStr1
}
#IBAction func changeLabel(sender: AnyObject) {
}
I have no more ideas what I am doing wrong. Thank you for your help.
The problem is this line:
let Vc = ViewController()
You are creating a new instance — a new ViewController instance. That's not what you want to do. You want to get a reference to an existing instance — the one that is your view controller's parent view controller, if that's what a View Controller is in relation to your TableViewController.
You better instance your ViewController form StoryBoard and define what you want to pass as property, and then set this property to the value that you need to show, and in the viewDidLoad of your ViewController update your view as you need

Swift - Set a UI element from outside

I have this UIViewController
import UIKit
class UIViewController1: UIViewController {
#IBOutlet weak var someTitle: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
And I am trying to set someTitle when I instantiate it from another view controller:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(animated: Bool) {
let stb = UIStoryboard(name: "Main", bundle: nil)
let vc1 = stb.instantiateViewControllerWithIdentifier("someSTBID") as! UIViewController1
vc1.someTitle.text = "My Title" // it fails here!!!!!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The reason it fails at the line above is that I was trying to force unwrapping a nil optional, which is someTitle.
Please show me a way to set someTitle in this situation.
Your second UIViewController hasn't been loaded yet, so the someTitle IBOutlet will be nil. You got two options:
The easy one: you force the load of the second UIViewController, for example: vc1.view is enough and then you set it (I don't recommend this)
The proper one: you let the second UIViewController be responsible for setting its own title at the right time. If you need to pass the "My title", you can simply pass it via a function like configureVc(title: String), or by exposing a variable like var title: String, so on viewDidLoad of the second UIViewController you would someTitle.text = title.
Do you need it to go into the superclass viewDidAppear, because it should work if you put it into the superclass viewDidLoad(). I hope that helps you and future viewers.

Text from TextBox to Widget?

So i am making an iOS app, that lets you to enter text into a TextBox and then there is a Button that will display the "Text" on a label, and that "Text" on the label will be Displayed in the Notification Center, on a widget, But something is going wrong Because every time i run the app it fails and throws me into the AppDelegate.Swift and highlights me this specific part: "class AppDelegate: UIResponder, UIApplicationDelegate {"
with an error that says "Thread 1: signal SIGABRT"
i Don't know what else to do ;( please help!!
This is the ViewController.Swift code:
import UIKit
class ViewController: UIViewController {
#IBOutlet var UserInput: UITextField!
#IBOutlet var TextDisplay: UILabel!
#IBAction func DisplayButton(sender: AnyObject) {
let Text:String = UserInput.text!
if let Text = Int(Text) {
print("Computer says no!")
} else {
TextDisplay.text = (Text)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let SharedDefaults = NSUserDefaults(suiteName: "group.St33v3n.TextOnWidget")
SharedDefaults?.setObject(UserInput, forKey: "StringKey")
SharedDefaults?.synchronize()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
and Here is the TodayView controller code (the one from the widget):
import UIKit
import NotificationCenter
class TodayViewController: UIViewController, NCWidgetProviding {
#IBOutlet var TextToWidget: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view from its nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) {
let ShareDefaults = NSUserDefaults(suiteName:"group.St33v3n.TextOnWidget")
self.TextToWidget.text = ShareDefaults?.objectForKey("StringKey") as? String
completionHandler(NCUpdateResult.NewData)
}
}
In the line
SharedDefaults?.setObject(UserInput, forKey: "StringKey")
you are passing UITextField object, not the text. You should use
SharedDefaults?.setObject(UserInput.text, forKey: "StringKey")
I'm not sure if that is causing the crash, but it needs correction anyway ;)

Delegate Not Called In SWIFT iOS

I am Created 2 Views, One is and Used Protocol and Delegate. For first view the Delegate function is not called.
My FirstView Controller : Here I am Accessing the Delegate Function.
import UIKit
class NextViewController: UIViewController,DurationSelectDelegate {
//var secondController: DurationDel?
var secondController: DurationDel = DurationDel()
#IBAction func Next(sender : AnyObject)
{
let nextViewController = DurationDel(nibName: "DurationDel", bundle: nil)
self.navigationController.pushViewController(nextViewController, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
secondController.delegate=self
}
func DurationSelected() {
println("SUCCESS")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
My SecondView Controller : Here I Am creating Delegate.
import UIKit
protocol DurationSelectDelegate {
func DurationSelected()
}
class DurationDel: UIViewController {
var delegate: DurationSelectDelegate?
#IBAction func Previous(sender : AnyObject) {
//let game = DurationSelectDelegate()
delegate?.DurationSelected()
self.navigationController.popViewControllerAnimated(true)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
To me, it looks like you're pushing a view controller that you haven't actually set the delegate for. If you change your "Next" function, to include the line
nextViewController.delegate = self
You should see that the delegation works. In doing this, you can also probably remove the creation of "secondController", as it looks like that's redundant.
The naming convention you have followed would confuse fellow developers in your team. The instance should have been
let durationDel = DurationDel(nibName: "DurationDel", bundle: nil)
And then as #Eagerod mentioned, the delegate you would set is
durationDel.delegate = self

Resources