分发应用程序时将文本文件放在哪里?

Where to put the text files when I distribute the app?

我有一个简单的应用程序需要读取多个文本文件。但是现在为了访问这些文件,我给出了笔记本电脑中文件的地址。

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.
}

}

只需将它们放入您的应用程序包中,然后您就可以阅读它们:

NSString *filePath = [[NSBundle mainBundle] pathForResource:  "science" ofType:@"txt"];
NSData *data = [NSData dataWithContentsOfFile:filePath];

    if let filepath = Bundle.main.path(forResource: "science", ofType: "txt")
    {
        let data = NSData.init(contentsOfFile: filepath)
        NSLog("\(data)")
    }

您可以将它们拖放到 Xcode 的导航区域,确保它们包含在 Xcode 的构建阶段 |复制捆绑资源。

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))
 }