如何在Xcode 6.1中使用Swift中的NSURL?

时间:2022-10-30 14:45:00

What am I doing wrong? I am trying to use an api, but first I need to learn to do http stuff in swift.

我究竟做错了什么?我正在尝试使用api,但首先我需要学习在swift中做http的东西。

I am using this code in the playground:

我在操场上使用此代码:

// 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://*.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)
}

and getting these errors in the console:

并在控制台中获取这些错误:

Playground execution failed: <EXPR>:12:11: error: use of unresolved identifier 'NSURL'
let url = NSURL(string: "http://www.*.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))

1 个解决方案

#1


9  

You need to import Foundation framework to make those types available. So add following import line to your playground:

您需要导入Foundation框架才能使这些类型可用。因此,将以下导入行添加到您的游乐场:

import Foundation

#1


9  

You need to import Foundation framework to make those types available. So add following import line to your playground:

您需要导入Foundation框架才能使这些类型可用。因此,将以下导入行添加到您的游乐场:

import Foundation