2

I am very new to obj c/swift and trying to connect to a RESTful api and keep getting fatal error "unexpectedly found nil while unwrapping an Optional value" at this point:

var request = NSURLRequest(URL: url!)

I am using this example to complete the task - https://stackoverflow.com/a/24495548/4375598. I am attempting to use a username and password to log into an app with a private api_key within the url.

import UIKit

class ViewController: UIViewController, NSURLConnectionDataDelegate {

@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!


@IBAction func signInButton(sender: AnyObject) {
    var url = NSURL(string: "MY URL")
    var request = NSURLRequest(URL: url!)
    var connection = NSURLConnection(request: request, delegate: self, startImmediately: true)

}

func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge!) {
    if challenge.previousFailureCount > 1 {

    } else {
        let creds = NSURLCredential(user: usernameTextField.text, password: passwordTextField.text, persistence: NSURLCredentialPersistence.None)
        challenge.sender.useCredential(creds, forAuthenticationChallenge: challenge)
    }
}

func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse) {
    let status = (response as NSHTTPURLResponse).statusCode
    println("status code is \(status)")
}
Community
  • 1
  • 1

2 Answers2

0

I assume you've got an actual URL that you pass in to your NSURL initializer? You are forcibly unwrapping that url which may be the cause of the "unexpectedly found nil" error, because NSURL's initializer may fail. Use if let binding to unwrap the optional if it is valid.

BJ Miller
  • 1,536
  • 12
  • 16
0

The URL that you use ("MY URL") should be well formatted and, according to Apple, comply with RFC2396.

If the URL is not well formatted NSURL will return nil. The next line will fail because you do a forced unwrapping of url variable (purpose of the exclamation mark (!)). If you do a forced unwrapping on a variable that is set to nil, like in NSURLRequest, your app will crash at runtime returning "unexpectedly found nil while unwrapping an Optional value"

if you wan to check if the variable is correctly initialized and not set to nil you can do the following:

if let url = NSURL(string: "MY URL") {
    var request = NSURLRequest(URL: url!)
    var connection = NSURLConnection(request: request, delegate: self, startImmediately: true)
}
else {
    println("url is set to nil)
}

To immediately solve your issue, make sure that your url is well formatted

Jérôme
  • 8,016
  • 4
  • 29
  • 35