我正在尝试调用使用 HTTP Basic Auth 的本地 Rest 服务。
根据我的要求,我得到以下信息:
发现:错误 - 未经授权
发现:原因 - 需要密码
这是我正在执行请求的函数。
func connect(url: String) -> Bool {
let url: NSURL = NSURL(string: url);
let login:String = "admin";
let password:String = "test123";
var defaultCredentials: NSURLCredential = NSURLCredential(user: login, password: password, persistence: NSURLCredentialPersistence.ForSession);
let host: String = url.host;
let port: Int = url.port;
let prot: String = url.scheme;
println("set following vars \(host) + \(port) + \(prot)");
var protectionSpace: NSURLProtectionSpace = NSURLProtectionSpace(host: host,port: port,`protocol`: prot,realm: nil,authenticationMethod: NSURLAuthenticationMethodHTTPBasic);
var credentialStorage: NSURLCredentialStorage = NSURLCredentialStorage.sharedCredentialStorage();
credentialStorage.setCredential(defaultCredentials, forProtectionSpace: protectionSpace);
var sessionConfiguration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration();
sessionConfiguration.URLCredentialStorage = credentialStorage;
let session: NSURLSession = NSURLSession(configuration: sessionConfiguration); //NSURLSession.sharedSession()
//NSURLSession.sessionWithConfiguration(sessionConfiguration);
let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
println("Task completed")
if((error) != nil) {
// If there is an error in the web request, print it to the console
println(error.localizedDescription)
}
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
if(err != nil) {
// If there is an error parsing JSON, print it to the console
println("JSON Error \(err!.localizedDescription)")
}
self.delegate.didReceiveAPIResults(jsonResult);
})
task.resume()
return true
}
有人可以给我一个提示吗?