0

I am using a Smart App Banner to promote an application and it works well! However, I would like to load the link i’m navigating in my webView(I am using a WKWebView) when clinking on the Smart App Banner.

Here is the following code that I am using in my AppDelegate.swift file:

var vc = ViewController()

func application(application: UIApplication, openURL url: NSURL,sourceApplication: String?, annotation: AnyObject) -> Bool {

let url1 = NSURL(string:"\(url)")!

self.vc.webView!.loadRequest(NSURLRequest(URL: url1!))
return true
}

and it's not working!

S.D
  • 93
  • 1
  • 1
  • 11
  • you show the viewcontroller, adding it to navigationController or showing it as a modal? – GeekRiky May 04 '16 at 09:25
  • I've got only one viewcontroller in the application that i've used to display my webView. – S.D May 04 '16 at 09:57
  • Usually your view controller is a class in a separate file. In app delegate you can post a notification and in the view controller observe it. For use NSNotificationCenter in swift: [http://stackoverflow.com/a/24756761/4519092](http://stackoverflow.com/a/24756761/4519092) – GeekRiky May 04 '16 at 10:43
  • It appears that the value of my webView returns nil, thats why i'm getting this error! – S.D May 04 '16 at 11:07
  • Yes because you create view controller by: ```var vc = ViewController()```. Are you using storyboard? – GeekRiky May 04 '16 at 11:09
  • Yes I am using the storyboard. If I remove 'var vc = ViewController()' , how to call the webView? – S.D May 04 '16 at 11:25

1 Answers1

2

You can try this:

in app delegate:

func application(application: UIApplication, openURL url: NSURL,sourceApplication: String?, annotation: AnyObject) -> Bool {

let url1 = NSURL(string:"\(url)")!

NSNotificationCenter.defaultCenter().postNotificationName("OpenLinkNotification", object: url1)

return true
}

in the view controller:

override func viewDidLoad() {
        super.viewDidLoad()

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "methodOfReceivedNotification:", name:"OpenLinkNotification", object: nil)
       ...
}

...

func methodOfReceivedNotification(notification: NSNotification){
    let url = notification.object as NSURL
    self.vc.webView!.loadRequest(NSURLRequest(URL: url!))
}

override func viewDidDisappear(animated: Bool) {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}
GeekRiky
  • 375
  • 3
  • 12