use*_*270 12 api ios nsurlsession swift
我正在尝试学习在Swift中使用API.作为一个很好的第一次测试,我想我已经点击itunes API并返回一些搜索结果.我在游乐场使用以下代码.我没有任何错误,但我的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()
Run Code Online (Sandbox Code Playgroud)
小智 26
尝试添加以下代码行:
URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)
Run Code Online (Sandbox Code Playgroud)
pva*_*len 21
对于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)
Run Code Online (Sandbox Code Playgroud)
小智 11
Swift 3代码:
<!-- language: lang-c -->
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
Run Code Online (Sandbox Code Playgroud)
尝试以下行,我猜它会工作:
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
Run Code Online (Sandbox Code Playgroud)
不知道为什么你没有看到错误\xe2\x80\x94我得到这个:
\n\nNSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9807)
您可以使用 httpbin.org\xe2\x80\x94 更有效地进行测试,这对我来说非常有用:
\n\nlet url = NSURL(string: "http://httpbin.org/get")\n\nlet task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in\n println(NSString(data: data, encoding: NSUTF8StringEncoding))\n}\n\ntask.resume()\nRun Code Online (Sandbox Code Playgroud)\n