簡體   English   中英

Mac OsX控制台應用程序NSURLSession Ssl問題

[英]Mac OsX Console Application NSURLSession Ssl Issue

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

祝你今天愉快 !

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM