2016-02-03 2 views
0

Привет в моей консоли Приложения OS X Я пытаюсь подключиться к веб-службе, на которой размещается https. Я не могу подключить этот веб-сервис с кодом ниже. Странная вещь, если я использую тот же класс в обычном какао-приложении. он отлично работает. Есть ли у вас какие-либо идеи, в чем проблема?Mac OS X Console Application NSURLSession Ssl Issue

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) 
+3

'Я не могу подключиться' Что это значит: ничего не происходит? Нет сообщения об ошибке? Нет симптомов вообще? Пожалуйста, сообщите подробности. Благодарю. – Moritz

+0

Да ничего не происходит, никаких ошибок. Просто я подозреваю об угрозе. Поскольку это консольное приложение, возможно, главная угроза уже выполнена перед ответом. – SerhatTopkaya

+0

Действительно, это может быть причиной. Related: http://stackoverflow.com/questions/25126471/cfrunloop-in-swift-command-line-program – Moritz

ответ

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

Иметь хороший день!