Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use NSURL in Swift in Xcode 6.1?

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

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

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.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))
like image 478
webmagnets Avatar asked Nov 13 '14 13:11

webmagnets


1 Answers

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

import Foundation
like image 179
Vladimir Avatar answered Oct 07 '22 03:10

Vladimir