2014-11-07 23 views
5

Desidero leggere e visualizzare il contenuto di un file di testo che si trova in un URL. Sto codificando un'applicazione Mac per Yosemite e ho bisogno di usare Swift ma mi sono bloccato su questo.Leggere un file di testo con NSURL in Swift

Ecco il mio codice:

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


    }) 

ho cercato di farlo con NSString.stringWithContentsOfURL ma sembra essere deprecato su OS X 10.10.

Il file di testo situato sul server ha solo una linea (UTF8).

Qualsiasi indizio? Grazie

risposta

2

Hai chiamato 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 
+0

Ahhh la chiamata di ripristino(). Ha funzionato! Grazie – Romain

+0

Che dire se l'url sta puntando al file locale come "file: ///Users/adrian/desktop/readme.txt"? –

+0

@AdrianHoe: Per questo è sufficiente utilizzare String (contentsOf: URL). In effetti, puoi probabilmente usarlo per recuperare gli URL remoti, ma non l'ho provato. – rjcarr

Problemi correlati