0

I'm trying to change my WebView URL, but every time I get fatal error: unexpectedly found nil while unwrapping an Optional value.

What's wrong? Thanks.

@IBOutlet weak var myWebView: UIWebView!
override func viewDidLoad() {
    super.viewDidLoad()
    myWebView.delegate = self
    let url = NSURL (string: "http://cnn.com");
    let requestObj = NSURLRequest(url: url! as URL);
    myWebView.loadRequest(requestObj as URLRequest);

}

func changeURL(urlIncome:String) {
        let url = NSURL(string: urlIncome)
        let requestObj = NSURLRequest(url: url as! URL)
        myWebView.loadRequest(requestObj as URLRequest);
}

My AppDelegate code:

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
var vc = ViewController()


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    UIApplication.shared.statusBarStyle = .lightContent

    OneSignal.initWithLaunchOptions(launchOptions, appId: "", handleNotificationReceived: { (notification) in

        let payload = notification?.payload
        //let fullMessage = payload?.title
        if let additionalData = payload?.additionalData, let actionURL = additionalData["url"] as? String {
            self.vc.changeURL(urlIncome: actionURL);
        }

    }, handleNotificationAction: { (result) in

        // This block gets called when the user reacts to a notification received
        let payload = result?.notification.payload
        let fullMessage = payload?.title

        NSLog(fullMessage!);

    }, settings: [kOSSettingsKeyAutoPrompt : true, kOSSettingsKeyInFocusDisplayOption : false])



    // Override point for customization after application launch.
    return true
}
Lucas Veiga
  • 1,758
  • 7
  • 27
  • 45

2 Answers2

0

The reason why its crashing is because you are force casting URL and URL request.

Change the below code

let url = NSURL (string: "http://cnn.com");
let requestObj = NSURLRequest(url: url! as URL);
myWebView.loadRequest(requestObj as URLRequest);

to

let url = URL(string: "http://google.com")!
myWebView.loadRequest(URLRequest(url: url))
Parth Adroja
  • 13,198
  • 5
  • 37
  • 71
0

This is a code I've just tested in Swift 3 with Deployment Target 9.0 set into General tab in XCode 8.2. It works smoothly, hope this helps:

your ViewController.swift:

var myUrl = ""

override func viewDidLoad() {
        super.viewDidLoad()

        if myUrl == "" {
let url = URL (string: "http://cnn.com")
webView.delegate = self
webView.loadRequest(URLRequest(url: url!)) 
} else {
let url = URL (string: myUrl)
webView.delegate = self
webView.loadRequest(URLRequest(url: url!)) 
}

    }

AppDelegate:

if let additionalData = payload?.additionalData, let actionURL = additionalData["url"] as? String {
            let mainStoryboardIpad : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
         let myVC : UIViewController = mainStoryboardIpad.instantiateViewControllerWithIdentifier("ViewController") as UIViewController
myVC.myUrl = actionURL
         self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
         self.window?.rootViewController = initialViewControlleripad
         self.window?.makeKeyAndVisible()
        }

Also remember to add App Transport Security into your Info.plist file in order to allow Arbitrary Loads (unless you've already done that :)

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>
Frank Eno
  • 2,581
  • 2
  • 31
  • 54
  • Simply doesn't work. I'm calling the changeURL from my AppDelegate when I receive a push. – Lucas Veiga Dec 22 '16 at 17:36
  • Show the code in the app delegate where you are calling `changeURL`. You're probably doing it wrong there which is causing `myWebView` to be `nil`. – dan Dec 22 '16 at 17:39
  • ok, i thought you called that changeURL() func from the same swift file that hosts your webView. Then you should check if the code you have for received notifications works fine with a print() func, and post that code as @dan said – Frank Eno Dec 22 '16 at 17:40
  • @dan Updated my question. Sorry for forgetting that guys. – Lucas Veiga Dec 22 '16 at 17:50
  • ok so first put a print(actionURL) into if let additionalData and check if prints something. if not, that's where the error is, and you should check the OneSignal documentation or contact them, they usually reply within a day – Frank Eno Dec 22 '16 at 18:23
  • @fvimagination Prints the url I expect. – Lucas Veiga Dec 22 '16 at 18:31
  • @fvimagination It gives me 2 errors in code: `Value of type 'UIViewController' has no member 'myUrl'` in `myVC.myUrl = actionURL` and `Use of unresolved identifier 'initialViewControlleripad` – Lucas Veiga Dec 23 '16 at 01:38
  • have you added the "ViewController" Storyboard ID in the inspector panel? http://timdietrich.me/fmblog/assets/swift-multiple-storyboards-03.png – Frank Eno Dec 23 '16 at 06:45
  • @fvimagination Yes, I am. – Lucas Veiga Dec 23 '16 at 13:55