【发布时间】:2014-12-18 20:52:55
【问题描述】:
我对 obj c/swift 非常陌生,并尝试连接到 RESTful api 并在这一点上不断收到致命错误“在展开可选值时意外发现 nil”:
var request = NSURLRequest(URL: url!)
我正在使用这个示例来完成任务 - https://stackoverflow.com/a/24495548/4375598。我正在尝试使用用户名和密码登录到带有 url 中私有 api_key 的应用程序。
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)")
}
【问题讨论】:
标签: swift