Mac OSX 控制台应用程序 NSURLSession ssl 问题



嗨,在我的控制台OS X应用程序中,我尝试连接托管https的Web服务。我无法用下面的代码连接该 Web 服务。奇怪的是,如果我在普通的可可应用程序中使用相同的类。它工作正常。你知道问题出在哪里吗?

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

有好的一天!

最新更新