Search code examples
swift2nsurlnsurlsessionnsurlrequest

NSURL always returning nil Swift 2.0


In an app I am making, I have a line of code that looks like this:

let url = NSURL(string: "https://website.com/api/loginauth?username=\(usernameField.text)&password=\(passwordField.text)")
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let request = NSURLRequest(URL: url!)

Every time this code gets executed, the app crashes with an Error that looks like this:

fatal error: unexpectedly found nil while unwrapping an Optional value

The URL is clearly not nil, but it crashes each time when unwrapping the url at NSURLRequest().

Thanks in advance


Solution

  • Thanks Eric D. and vadian for answering my question, the answer is that usernameField.text and passwordField.text need to be unwrapped, so when I did this, it worked perfectly:

    let url = NSURL(string: "https://website.com/api/loginauth?username=\(usernameField.text!)&password=\(passwordField.text!)")
    let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
    let request = NSURLRequest(URL: url!)
    

    Thanks so much -