您好,在我的控制台 OS X 应用程序中,我尝试连接托管 https 的 Web 服务。我无法使用以下代码连接该 Web 服务。 奇怪的是,如果我在普通的 cocoa 应用程序中使用相同的类。它工作正常。你知道问题出在哪里吗?
import Foundation
class Service : NSObject , NSURLSessionDelegate {
func httpGet(request: NSMutableURLRequest!) {
let configuration =
NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue:NSOperationQueue.mainQueue())
let task = session.dataTaskWithRequest(request){
(data, response, error) -> Void in
print("ok data taken")
}
task.resume()
}
func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!))
}}
let service = Service()
service.httpGet(NSMutableURLRequest(URL: NSURL(string: "http://www.google.com")!))
sleep(10)
最佳答案
我用下面的代码解决了这个问题:)
class Service : NSObject , NSURLSessionDelegate {
func httpGet(request: NSMutableURLRequest!) {
let s = dispatch_semaphore_create(0)
let configuration =
NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue:nil)
let task = session.dataTaskWithRequest(request){
(data, response, error) -> Void in
dispatch_semaphore_signal(s)
print("ok data taken")
}
task.resume()
dispatch_semaphore_wait(s, dispatch_time(DISPATCH_TIME_NOW, AppConstants.Values.SemephoreTimeOut))
}
func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!))
}}
祝你有美好的一天!
关于swift - Mac OsX 控制台应用程序 NSURLSession Ssl 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35182113/