I have implemented three 3D touch actions, lets name them app.touch1
, app.touch2
and app.touch3
.
This is the code in my AppDelegate
file:
func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) {
if(shortcutItem.type == "app.touch1"){
MyVariables.url = "https://google.de/";
} else if(shortcutItem.type == "app.touch2") {
MyVariables.url = "https://yahoo.de/";
} else if(shortcutItem.type == "app.touch3") {
MyVariables.url = "https://bing.de/";
}
}
This is my MyVariables
class for now:
struct MyVariables {
static var url = "https://test.de/"
}
This is the code of my ViewController
class:
IBOutlet var containerView : UIView?
var webView: UIWebView?
var loadedURL: String?
override func prefersStatusBarHidden() -> Bool {
return true
}
override func loadView() {
super.loadView()
self.webView = UIWebView()
self.view = self.webView!
}
override func viewDidLoad() {
super.viewDidLoad()
load()
}
func load() {
let requestURL = NSURL(string: MyVariables.url)
let request = NSURLRequest(URL: requestURL!)
self.webView!.loadRequest(request)
loadedURL = MyVariables.url
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
However, it always loads the default url (https://test.de/
), even if the app was closed before. I tried events like viewDidAppear
and viewWillAppear
also, but this did not work.
I think this is very simple for an iOS developer - I tried to start with iOS and have this problem :-(
The problem is that your ViewController class is being loaded before the App Delegate has finished launching (because it's the root view controller), so the code that sets the URL hasn't been called at the point that you make the request.
What you need to do is either make performActionForShortcutItem start the request on the ViewController, or find another way to trigger that code.
So its look like this is only a problem with your struct?
I would try to set a global variable in your AppDelegate, and then use it in your ViewController.
For example:
Create an url variable in your AppDelegate.
In your ViewController use:
func load() {
let delegate = UIApplication.sharedApplication().delegate as AppDelegate
let requestURL = NSURL(string: delegate.url)
let request = NSURLRequest(URL: requestURL!)
self.webView!.loadRequest(request)
loadedURL = MyVariables.url
}
Try it out, it should work. Another idea would be to store it as Singleton, check this out here:
https://github.com/hpique/SwiftSingleton
Or (it depends on your data you want to archive) -> store it as NSUserDefaults()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With