在快速HTTP请求不工作
我正在尝试了解如何在Swift中使用API。 作为一个很好的第一个testing,我想我会打iTunes的API,只是返回一些search结果。 我在操场上使用下面的代码。 我没有得到任何错误,但我的println不输出任何东西。 任何人都知道什么是错的?
谢谢!
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()
尝试添加这一行代码:
URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)
对于Swift 3 / Xcode 8.2.1,结合几个答案(rv1331,Wouter van Zuilen)给出了最好的结果,在Playground中没有错误。 我正在使用这个Swift 3 REST示例:
import PlaygroundSupport import Foundation PlaygroundPage.current.needsIndefiniteExecution = true URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)
Swift 3代码:
<!-- language: lang-c --> import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true
尝试下面的行,我想这将工作:
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
不知道为什么你没有看到一个错误 – 我得到这个:
NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9807)
你可以用httpbin.org更有效地testing – 这对我来说是完美的:
let url = NSURL(string: "http://httpbin.org/get") let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in println(NSString(data: data, encoding: NSUTF8StringEncoding)) } task.resume()
我的回答是不正确的,它只是在playgound无限期的页面执行。 会话types无关紧要。
最近遇到同样的问题,并find一个解决scheme。
该错误是由使用URLSession.shared()
,这是显然不允许在操场沙箱造成的。
创build并使用您自己的临时URL会话:
let session = URLSession(configuration: URLSessionConfiguration.ephemeral)