Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP Request in swift not working

I'm trying to learn about working with APIs in Swift. As a good first test, I figured I'd hit the itunes API and just return some search results. I'm in playground using the following code. I don't get any errors, but my println isn't outputting anything. Anyone know what's wrong?

Thanks!

import UIKit
import XCPlayground

XCPSetExecutionShouldContinueIndefinitely()


let url = NSURL(string: "https://itunes.apple.com/lookup?id=909253")

let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
    println(NSString(data: data, encoding: NSUTF8StringEncoding))
}

task.resume()
like image 307
user2874270 Avatar asked Feb 05 '15 19:02

user2874270


2 Answers

try following line and i guess it will work:

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
like image 122
Jasmin Avatar answered Oct 05 '22 22:10

Jasmin


For Swift 3/Xcode 8.2.1, combining a couple of the answers (rv1331, Wouter van Zuilen) gave the best results with no errors in Playground. I'm using this Swift 3 REST example:

http://mrgott.com/swift-programing/30-work-with-rest-api-in-swift-3-and-xcode-8-using-urlsession-and-jsonserialization

import PlaygroundSupport
import Foundation

PlaygroundPage.current.needsIndefiniteExecution = true
URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)
like image 43
pvanallen Avatar answered Oct 05 '22 23:10

pvanallen