In my Browser app I want to make the URL Scheme of my app (myapp://) to open URLs that come after the myapp://
part.
I want to have a user use myapp://http://google.com
and it will open Google.
I set up the URL scheme itself in the app's Info.plist file, and it works (using myapp:// in Safari launches the app). I set up my App Delegate with this function from this question:
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
if let string = url.absoluteString {
let value = string[string.endIndex ..< string.endIndex]
NSUserDefaults.standardUserDefaults().setObject(value, forKey: AppDefaultKeys.URLSchemeRecievedURL.rawValue)
return true
}
return false
}
then, I set up my main ViewController (where the view resides) with this code in the viewDidLoad function:
var _urlSchemeRecievedURL = NSUserDefaults.standardUserDefaults().stringForKey(AppDefaultKeys.URLSchemeRecievedURL.rawValue)
if _urlSchemeRecievedURL != nil {
loadURL(_urlSchemeRecievedURL!)
}
This is the code for the loadURL function:
func loadURL(urlString: String) {
let addr = NSURL(string: urlString)
if let webAddr = addr {
let req = NSURLRequest(URL: webAddr)
_webView!.loadRequest(req)
} else {
displayLoadingErrorMessage()
}
}
I used NSUserDefaults since it's the way only way I currently know how to pass data from AppDelegate to my ViewController.
Something isn't working though, since when I use myapp://http://google.com
in Safari it only launches the app (without google.com being loaded).
I also tried using this code:
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
if let string = url.absoluteString {
if let range = string.rangeOfString("q=") {
let value = string[range.endIndex ..< string.endIndex]
NSUserDefaults.standardUserDefaults().setObject(value, forKey: AppDefaultKeys.URLSchemeRecievedURL.rawValue)
return true
}
}
return false
}
With myapp://?q=http://google.com
but it doesn't work too.
UPDATE:
Using the code with the ?q=
query works, but only on the next launch.
And after the next launch, the app always launches with did URL (since it's saved in NSUserDefaults).
So the question now is, How can I pass the URL from the AppDelegate to ViewController without NSUserDefaults?
Thanks,
PastaCoder