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)")
}