【问题标题】:Reading file from txt file but is not inside the Xcode project从 txt 文件中读取文件但不在 Xcode 项目中
【发布时间】:2017-12-04 03:30:15
【问题描述】:

需要有关获取不在 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 的正确文件路径是什么?

【问题讨论】:

  • 应用是沙盒的。你的应用程序在你的 iPad 上,而你给它一个你的 Mac 的路径?毫无意义。
  • 那你知道画廊的文件路径吗?沙盒化的应用程序的文件路径是什么,或者不允许用户知道文件路径?我只是举了一个关于我的 Mac 路径的例子,因为我不知道要插入什么,所以我只是随机输入了我的 Mac 路径。

标签: ios xcode swift3 swift2


【解决方案1】:

iPhone 和 iPad 应用程序在各自的沙盒中运行。应用程序无权访问应用程序沙箱之外的资源。所以基本上文件是否在你的 Xcode 项目中并不重要(文件是否是主包的一部分并不重要,因为你也可以下载文件并编写它),但重要的是是否文件是否在您的应用程序的沙箱中。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-23
    • 2016-06-15
    相关资源
    最近更新 更多