从txt文件中读取文件但不在Xcode项目中

时间:2017-06-30 08:24:31

标签: ios xcode swift3 swift2

需要有关获取不在xcode项目中的txt文件的帮助。有没有办法在xcode项目中没有txt文件的情况下检索txt文件?

var  data:[[String:String]] = []
var  columnTitles:[String] = []

@IBOutlet weak var textView: UITextView!




override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

@IBAction func reportData(_ sender: Any) {
      printData()
}

@IBAction func resetData(_ sender: Any) {
     textView.text = "Nope, no Pizza here"
}


@IBAction func readData(_ sender: Any) {
      textView.text = readDataFromFile(file: "/Users/mpsip/Desktop/TextFileCSVDemo/data")
}


@IBAction func writeData(_ sender: Any) {
    if writeDataToFile(file: "data") {
        print("data written")
    } else {
        print("data not written")
    }
}


func cleanRows(file:String)->String{
    //use a uniform \n for end of lines.
    var cleanFile = file
    cleanFile = cleanFile.replacingOccurrences(of: "\r", with: "\n")
    cleanFile = cleanFile.replacingOccurrences(of: "\n\n", with: "\n")

    return cleanFile
}

func getStringFieldsForRow(row:String, delimiter:String)-> [String]{

    return row.components(separatedBy: delimiter)
}

func convertCSV(file:String){

    let rows = cleanRows(file: file).components(separatedBy: "\n")
    if rows.count > 0 {
        data = []
        columnTitles = getStringFieldsForRow(row: rows.first!,delimiter:",")
        for row in rows{
            let fields = getStringFieldsForRow(row: row,delimiter: ",")
            if fields.count != columnTitles.count {continue}
            var dataRow = [String:String]()
            for (index,field) in fields.enumerated(){
                dataRow[columnTitles[index]] = field
            }
            data += [dataRow]
        }
    } else {
        print("No data in file")
    }
}

func printData(){
    convertCSV(file: textView.text)
    var tableString = ""
    var rowString = ""
    print("data: \(data)")
    for row in data{
        rowString = ""
        for fieldName in columnTitles{
            guard let field = row[fieldName] else{
                print("field not found: \(fieldName)")
                continue
            }
            rowString += field + "\t"
        }
        tableString += rowString + "\n"
    }
    textView.text = tableString
}

//MARK: Data reading and writing functions
func writeDataToFile(file:String)-> Bool{
    // check our data exists
    guard let data = textView.text else {return false}
    print(data)
    //get the file path for the file in the bundle
    // if it doesnt exist, make it in the bundle
    var fileName = file + ".txt"
    if let filePath = Bundle.main.path(forResource: file, ofType: "txt"){
        fileName = filePath
    } else {
        fileName = Bundle.main.bundlePath + fileName
    }

    //write the file, return true if it works, false otherwise.
    do{
        try data.write(toFile: fileName, atomically: true, encoding: String.Encoding.utf8 )
        return true
    } catch{
        return false
    }
}

func readDataFromFile(file:String)-> String!{
    guard let filepath = Bundle.main.path(forResource: file, ofType: "txt")
        else {
            return nil
    }
    do {

       // let contents = try String(contentsOfFile: filepath, usedEncoding: String.Encoding.)


        let contents = try String (contentsOfFile: filepath, encoding: String.Encoding.utf8)
        return contents
    } catch {
        print ("File Read Error")
        return nil
    }
}

对于这条线 textView.text = readDataFromFile(file:" / Users / mpsip / Desktop / TextFileCSVDemo / data") 我怎么知道我的应用程序或iPad的正确文件路径是什么?

1 个答案:

答案 0 :(得分:0)

iPhone和iPad应用程序在自己的沙箱中运行。应用程序无权访问应用程序沙箱外的资源。所以基本上文件是否是他们在你的Xcode项目中并不重要(文件是否是主要包的一部分并不重要,因为你可以下载文件并将其写入),重要的是,无论是否文件是否在您应用的沙箱中。

如果该文件存在于app的document / temp目录中,则可以阅读该文件。您可以在应用程序启动时从托管服务器动态下载文件,并将其写入应用程序的document / temp目录并随时读取,或者将文件添加到应用程序包(将文件添加到Xcode项目)和发货。