Read file in swift, iOS playground

后端 未结 2 854
一向
一向 2021-01-01 23:55

Having searched through the many (many!) swift playground questions to even craft this code, I\'m still struggling.

I\'ve placed a text file in the Re

2条回答
  •  情话喂你
    2021-01-02 00:26

    I have seen this problem with .txt files created from .rtf files using TextEdit.

    I loaded a text.txt file in the resources folder of my playground using similar code to you. The file contents was "hello there" and was made by converting an .rtf file to .txt by changing the extension.

    let path = NSBundle.mainBundle().pathForResource("text", ofType: "txt")//or rtf for an rtf file
    var text = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)!
    println(text)
    

    The output was:

    {\rtf1\ansi\ansicpg1252\cocoartf1343\cocoasubrtf140 {\fonttbl\f0\fswiss\fcharset0 Helvetica;} {\colortbl;\red255\green255\blue255;} \margl1440\margr1440\vieww10800\viewh8400\viewkind0 \pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural

    \f0\fs24 \cf0 hello there}

    So the "hello there" is embedded. This is the problem with all the layout information in a .rtf file.

    I went back to TextEdit and created a true .txt file. After opening a file - Format|Make Plain Text

    Now this same code gave the console output "hello there".

提交回复
热议问题