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

标签 swift macos cocoa ssl

您好,在我的控制台 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/

相关文章:

swift - 从网络 URL 读取文本文件

ruby-on-rails - 使用 Brew 安装 rbenv

objective-c - 绘图的 NSFont 高度

cocoa - 如何定制 NSSlider 以在 cocoa 中提供非线性比例?

macos - CoreAudio AudioQueue 停止问题

objective-c - "NSBinarySearchingFirstEqual = (1UL << 8)"在枚举定义中是什么意思?

Swift 3 - 表达式太复杂,无法在合理的时间内解决;考虑将表达式分解为不同的子表达式

ios - Xcode 6 UITableView 使 View 变黑

ios - Firebase 存储不显示图像

objective-c - 为什么这些 ARC 对象的行为不一致?