首页 > 解决方案 > 在 iphone 中使用 swift 读取文件

问题描述

我需要在我的 iphone 中使用 swift 读取文件。在我的计算机中,我使用此代码并正常运行。文件“test.txt”在我的桌面中。

import UIKit

class Controller: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        let sourcePath = URL(fileURLWithPath: "/Users/myname/Desktop", isDirectory: true)
        let file : URL = URL(fileURLWithPath: "test.txt", relativeTo: sourcePath)

        let filemgr = FileManager.default

        if filemgr.fileExists(atPath: file.path){
            do{
                //Code to Parse text
            } catch let error as NSError{
            print ("Error: \(error)")
            }
        }
    }
}

问题是我需要在我的 iphone 中读取这个文件。但我不知道哪个是读取文件的 URL。我可以在哪里保存文件,哪个是 URL?

谢谢

标签: iphoneswifturl

解决方案


1-将文本文件拖到项目中并选择copy Items If needed

2-用这个来阅读它

do {

    if let path  = Bundle.main.path(forResource: "fileName", ofType: "txt") {

        let str = try String(contentsOfFile:path, encoding: .utf8)

        print(str)
    }


}

catch  {

    print(error)
}

推荐阅读