加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:00:28 所属栏目:百科 来源:网络整理
导读:我想阅读并显示位于URL的文本文件的内容. 我正在为优胜美地编写Mac应用程序,我需要使用 Swift,但我坚持这一点. 这是我的代码: let messageURL = NSURL(string: "http://localhost:8888/text.txt")let sharedSession = NSURLSession.sharedSession()let down
我想阅读并显示位于URL的文本文件的内容.
我正在为优胜美地编写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!,error: NSError!) -> Void in

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

             println(urlContents)

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读