gpt4 book ai didi

macos - 在 Swift 中使用 NSURL 读取文本文件

转载 作者:IT王子 更新时间:2023-10-29 05:53:07 26 4
gpt4 key购买 nike

我想读取和显示位于 URL 的文本文件的内容。我正在为 Yosemite 编写一个 Mac 应用程序,我需要使用 Swift,但我坚持了这一点。

这是我的代码:

let messageURL = NSURL(string: "http://localhost:8888/text.txt")
let sharedSession = NSURLSession.sharedSession()
let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(messageURL!, completionHandler: { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in

var urlContents = NSString(contentsOfURL: location, encoding: NSUTF8StringEncoding, error: nil)

println((urlContents))


})

我试着用 NSString.stringWithContentsOfURL 来做,但它似乎在 OS X 10.10 上被弃用了。

位于服务器上的文本文件只有一行(UTF8)。

有什么线索吗?谢谢

最佳答案

您是否调用了 downloadTask.resume()

let messageURL = NSURL(string: "http://localhost:8888/text.txt")
let sharedSession = NSURLSession.sharedSession()
let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(messageURL!,
completionHandler: {
(location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in

var urlContents = NSString(contentsOfURL: location, encoding: NSUTF8StringEncoding, error: nil)

println(urlContents)

})
downloadTask.resume() // Call it and you should be able to see the text.txt content

关于macos - 在 Swift 中使用 NSURL 读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26797899/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com