Dónde colocar a.txt archivo y leer de él en un proyecto de IOS


Quiero poner una .archivo txt en mi proyecto Xcode Swift Iphone. Primero, simplemente lo arrastre y lo suelte desde mi escritorio a la carpeta de archivos de soporte del proyecto. ¿No hay una carpeta como en Android "activos", por lo que puedo colocar mis archivos en cualquier lugar que desee?

El archivo en mi ejemplo se llama README.txt que tiene un montón de líneas y párrafos.

Bastante simple, ahora quiero imprimir el contenido del README.txt archivo a una vista.

Cómo hago la función read y qué ruta debo insertar, si mi archivo está en el proyecto / SupportFiles / README.txt?

Muchas gracias!

Author: Felix Me, 2014-11-29

5 answers

let path = NSBundle.mainBundle().pathForResource("README", ofType: "txt")
textView.text = String(contentsOfFile: path, 
                             encoding: NSUTF8StringEncoding, 
                                error: nil)

Simplemente coloque el archivo en cualquier lugar en el navegador del proyecto y asegúrese de que se agregue al destino correcto.

Solo para ampliar la respuesta, también puede colocarlos en una carpeta y usar: + pathForResource: OfType: inDirectory: .

 33
Author: Mundi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-29 19:50:03

Recomendaría usar NSFileManager y soltar el archivo en cualquier lugar del proyecto:

if let path = NSBundle.mainBundle().pathForResource(name, ofType: "txt"){
    let fm = NSFileManager()
    let exists = fm.fileExistsAtPath(path)
    if(exists){
        let c = fm.contentsAtPath(path)
        let cString = NSString(data: c!, encoding: NSUTF8StringEncoding)
        ret = cString as! String
    }
}
 7
Author: Pierre-Yves Guillemet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-01 12:49:48

En Swift 3

guard let path = Bundle.main.path(forResource: "README", ofType: "txt") else {
  return
}

textView.text = try? String(contentsOfFile: path, encoding: String.Encoding.utf8)
 4
Author: mokagio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-26 02:39:29

Si define path's type y pone ! al final de la línea, no recibirá ninguna advertencia.

 let path:String = NSBundle.mainBundle().pathForResource("README", ofType: "txt")!
 textView.text = String(contentsOfFile: path,
                 encoding: NSUTF8StringEncoding,
                 error: nil)
 1
Author: fatihyildizhan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-08 12:12:33

Swift 4 (gracias a @Pierre-Yves Guillemet por el original)

Siempre y cuando el archivo esté en su proyecto (y tenga un .txt) esto funcionará (en este ejemplo, asumo " MyFile.txt " es un archivo que está en mi proyecto):

static func LoadFileAsString() -> ()
{        
    if let path = Bundle.main.path(forResource: "MyFile", ofType: "txt")
    {
        let fm = FileManager()
        let exists = fm.fileExists(atPath: path)
        if(exists){
            let content = fm.contents(atPath: path)
            let contentAsString = String(data: content!, encoding: String.Encoding.utf8)
        }
    }
}
 1
Author: Aggressor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-01 15:53:10