许多Cocoa和CocoaTouch方法都有完成回调,实现为Objective-C中的块和Swift中的闭包.但是,在Playground中尝试这些时,永远不会调用完成.例如:
// Playground - noun: a place where people can play
import Cocoa
import XCPlayground
let url = NSURL(string: "http://stackoverflow.com")
let request = NSURLRequest(URL: url)
NSURLConnection.sendAsynchronousRequest(request, queue:NSOperationQueue.currentQueue() {
response, maybeData, error in
// This block never gets called?
if let data = maybeData {
let contents = NSString(data:data, encoding:NSUTF8StringEncoding)
println(contents)
} else {
println(error.localizedDescription)
}
}
Run Code Online (Sandbox Code Playgroud)
我可以在我的Playground时间轴中看到控制台输出,但是println我的完成块永远不会被调用...
我知道这已经被问了很多次,我已阅读相当 一个 小 问题 ,并用Google搜索,但没有成功,到目前为止天。
我只想在桌面应用程序中加载一个本地 html 文件,事实是这个项目我需要一个 JS 库,其中大部分已经作为网页完成(css、js 和 html,不需要服务器端处理)。我不想强制应用程序从互联网服务器加载网页,以免强迫用户连接互联网。不用说,我在 Swift 和苹果开发方面完全没有经验。
现在这是我遇到的问题:
关于参数的 ide 抱怨,我似乎无法理解它们。
作为参考,这里是我最新代码的片段:
class AppDelegate: NSObject, NSApplicationDelegate
{
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var webView: WebView!
typealias NSSize = CGSize
func applicationDidFinishLaunching(aNotification: NSNotification?)
{
self.window.title = "Chess Study Room"
var try1 = "main.html";
println(try1);
var try2 = NSURL(string: try1)!;
println(try2);
var try3 =
NSBundle.URLForResource("main", withExtension: "html", subdirectory: "web", inBundleWithURL: try2);
println(try3);
var try4 = NSBundle.pathForResource("main", ofType: "html", inDirectory: "web");
println(try4);
var …Run Code Online (Sandbox Code Playgroud) 使用swift 2,新的语言.我的目标是向API发送一个简单的post请求,然后解析响应.我没有找到一个明确的方法来做到这一点,我所做的任何尝试都失败了.这是我有的:
func restURL() {
let xmlStr: String? = "<webservices><WebService type='test'><WSName>test</WSName><select>select * from receipts where id = '1234'</select></WebService></webservices>"
let session = NSURLSession.sharedSession()
let url = NSURL(string: "https://apiwebaddress.com/post" as String)!
let request = NSMutableURLRequest(URL: url)
let post:NSString = xmlStr!
let postData:NSData = post.dataUsingEncoding(NSUTF8StringEncoding)!
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue("0", forHTTPHeaderField: "Content-Length")
request.setValue("application/xml", forHTTPHeaderField: "Content-Type")
request.setValue("gzip,deflate", forHTTPHeaderField: "Accept-Encoding")
request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")
Run Code Online (Sandbox Code Playgroud)
我相信我把它设置正确,我想发送它然后在响应的主体中获取xml,但我不知道从这里去哪里.我读过的所有内容都被弃用或混淆.有人可以用简单的术语解释如何实现我的目标吗?提前致谢
我正在使用swift的iOS应用程序.我需要在应用程序启动时解析两个web api(XML),在此期间,我需要显示启动屏幕.所以我发送了一个同步请求来解析服务器上的数据.如果网络连接良好,那么应用程序正常工作但由于网络连接速度慢或从服务器加载数据需要20秒以上,它可以自动退出.如何解决这个问题.请提出建议.