2015-11-26 77 views
0

我是新來的Swift,我已經學會了基本的語法,並且我正在嘗試做更先進的東西。 我與代碼波紋管的第一次嘗試是做在URL http://www.test.com HTTP請求並獲取響應:swift 2 newbie:dataTaskWithRequest回調沒有執行?

//: Playground - noun: a place where people can play 

import UIKit 

var url : NSURL = NSURL(string: "http://www.test.com")! 
var request: NSURLRequest = NSURLRequest(URL: url) 
let config = NSURLSessionConfiguration.defaultSessionConfiguration() 
let session = NSURLSession(configuration: config) 
var responseString:NSString?; 

let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in 
    print("toto") 
    if error != nil { 
     print("error=\(error)") 
     return 
    } else { 
     print("response = \(response!)") 
     responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)! 
     print("responseString = \(responseString)") 
    } 

}); 

task.resume() 
print (responseString) 

當運行在Xcode代碼,「TOTO」不打印和responseString是nil,關於發生什麼問題的任何想法?

回答

4

你正在一個操場上運行它,你需要做一些額外的工作來獲得異步任務運行。

首先,進口XCPlayground:

import XCPlayground 

然後,在操場的結束,加入這一行:

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true 

這使執行的,因此它可以在附近等你完成塊操場即將發生。

對於Xcode中8:

import PlaygroundSupport 

PlaygroundPage.current.needsIndefiniteExecution = true 
+1

*」 ......在操場結束時,加入這一行... * - 這不要緊,你加線,它可以在以後任何地方導入聲明:-) –

+0

它工作!!!謝謝你,迅速上師:p –