我有一个简单的应用程序,需要读取多个文本文件。但是现在,为了访问这些文件,我给出了我笔记本电脑中文件的地址。
let path = "/Users/alimashreghi/Desktop/glossories/science.txt"
var text:String = ""
do{
   text = try NSString(contentsOfFile:path, encoding: NSUTF8StringEncoding) as String
}catch{
}现在,我关心的是我想什么时候发布这个应用程序。我应该把文本文件放在哪里,我应该如何读取它们,以确保它作为iPhone中的应用程序正常工作?
此外,我对分发swift应用程序了解不多。
    //
//  ViewController.swift
//  Test
//
//  Created by Ali Mashreghi on 2016-08-29.
//  Copyright © 2016 Ali Mashreghi. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
    override func viewDidLoad() {
    let data = NSData.init(contentsOfFile: "/Users/TestProj/science.txt") //prints Optional(4380)
    let data = NSData.init(contentsOfFile: "science.txt") //prints nil
    print(data?.length)
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}}

发布于 2020-09-30 07:26:29
Swift 5版本
func getDataFromBundleFile(_ fileName: String, ofType: String) -> Data? {
    guard let filePath = Bundle.main.path(forResource: fileName, ofType: ofType) else {
        return nil
    }
    return try? Data(contentsOf: URL(fileURLWithPath: filePath))
 }https://stackoverflow.com/questions/39195939
复制相似问题