如何在iOS9上进行http基本身份验证?

时间:2015-09-28 18:38:27

标签: json ssl swift2 xcode7 http-basic-authentication

我一直在尝试通过http基本身份验证将我的ios应用程序连接到我的restful Web API,但我无法连接。这是我的代码:

let URL = NSURL(string:"https://devWebsvc1.whateverYolo.local:11201/api/webcall")
let theRequest = NSMutableURLRequest(URL:URL)
let session = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration())
theRequest.HTTPMethod = "POST"
theRequest.addValue("application/json", forHTTPHeaderField:"Content-Type")
theRequest.addValue("application/json", forHTTPHeaderField:"Accept")


let credential = NSURLCredential(user:"username", password:"password", persistence: NSURLCredentialPersistence.ForSession)
let protectionSpace = NSURLProtectionSpace(Host: URL?.host)!, port:11201, 'protocol': URL?.scheme, realm: nil, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
let credentialStorage = NSURLCredentialStorage.sharedCredentialStorage()
credentialStorage.setDefaultCredential(credential,forProtectionSpace:protectionSpace)
theSession.configuration.URLCredentialsStorage = credentialStorage

let task = theSession.dataTaskWithRequest(theRequest, completionHandler : {data, response, error -> Void in 
if error != nil
{print("\(error)")}})

错误信息是: -

  

可选(错误域= NSURLErrorDomain代码= -1200“发生SSL错误,无法建立与服务器的安全连接。”UserInfo = {NSURLErrorFailingURLPeerTrustErrorKey =,NSLocalizedRecoverySuggestion =您还要连接到服务器吗? _kCFStreamErrorDomainKey = 3,_kCFStreamErrorCodeKey = -9802,NSErrorPeerCertificateChainKey = {type = immutable,count = 1,values =(   0:   )},NSUnderlyingError = 0x7fe023520170 {错误域= kCFErrorDomainCFNetwork代码= -1200 “(空)” 的UserInfo = {_ kCFStreamPropertySSLClientCertificateState = 0,kCFStreamPropertySSLPeerTrust =,_kCFNetworkCFStreamSSLErrorOriginalValue = -9802,_kCFStreamErrorDomainKey = 3,_kCFStreamErrorCodeKey = -9802,kCFStreamPropertySSLPeerCertificates = {类型=不可变,count = 1,值=(   0:   }}}},NSLocalizedDescription =发生了SSL错误,无法建立与服务器的安全连接。,NSErrorFailingURLKey = https://devwebsvc1.whateverYolo.local:11201/api/Device,NSErrorFailingURLStringKey = https://devwebsvc1.whateverYolo.local:11201/api/Device,NSErrorClientCertificateStateKey = 0})

你们知道这可能是什么错误吗?任何帮助表示赞赏。我顺便使用xcode 7。

1 个答案:

答案 0 :(得分:0)

错误可能在这一行: -

theRequest.addValue("application/json", forHTTPHeaderField:"Accept")

你应该去这个谷歌扩展程序,找到字段的价值"接受"

铬扩展://hgmloofddffdnphfgcellkdfbfbjeloo/RestClient.html

enter image description here

添加您的网址,用户名和密码,然后点击提交,找到您的所有标题字段都是正确的,请检查Content-Type的值

enter image description here