Mac OsX控制台应用程序NSURLSession Ssl问题

时间:2016-02-03 16:14:12

标签: swift macos cocoa ssl

您好,在我的控制台OS X应用程序中,我尝试连接托管https的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)

1 个答案:

答案 0 :(得分:1)

我用以下代码解决了这个问题:)

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

度过美好的一天!