Read a text file with NSURL in Swift

自作多情 提交于 2019-12-05 20:33:46

问题


I want to read and display the content of a text file that is located at an URL. I am coding a Mac App for Yosemite and I need to use Swift but I stuck on this.

Here is my code:

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))


    })

I tried to do it with NSString.stringWithContentsOfURL but it seems to be deprecated on OS X 10.10.

The text file located at on the server has only one line (UTF8).

Any clue? Thanks


回答1:


Did you call 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


来源:https://stackoverflow.com/questions/26797899/read-a-text-file-with-nsurl-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!