Read a text file using NSURL in Swift

I want to read and display the contents of a text file located at a url. I am coding a Mac app for Yosemite and I need to use Swift, but I stuck with 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 this with NSString.stringWithContentsOfURL, but it seems to be deprecated in OS X 10.10.

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

Any clue? Thanks

+6
source share
1 answer

Have you called 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 
+2
source

Source: https://habr.com/ru/post/977870/


All Articles