我做错了什么?我正在尝试使用api,但首先我需要学习swift中的http内容。
我在操场上使用此代码:
// Playground - noun: a place where people can play
// import Cocoa - this is commented out due to "No such module 'Cocoa'"
import XCPlayground
let url = NSURL(string: "http://stackoverflow.com")
let request = NSURLRequest(URL: url)
var waiting = true
NSURLConnection.sendAsynchronousRequest(request, queue:NSOperationQueue.currentQueue() {
response, maybeData, error in
waiting = false
if let data = maybeData {
let contents = NSString(data:data, encoding:NSUTF8StringEncoding)
println(contents)
} else {
println(error.localizedDescription)
}
}
while(waiting) {
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate())
usleep(10)
}
并在控制台中收到这些错误:
Playground execution failed: <EXPR>:12:11: error: use of unresolved identifier 'NSURL'
let url = NSURL(string: "http://www.stackoverflow.com")
^
<EXPR>:14:12: error: use of unresolved identifier 'NSURLSession'
let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in
^
<EXPR>:15:13: error: use of unresolved identifier 'NSString'
println(NSString(data: data, encoding: NSUTF8StringEncoding))
^
<EXPR>:15:44: error: use of unresolved identifier 'NSUTF8StringEncoding'
println(NSString(data: data, encoding: NSUTF8StringEncoding))
答案 0 :(得分:9)
您需要导入Foundation框架才能使这些类型可用。因此,将以下导入行添加到您的游乐场:
import Foundation