【问题标题】:Where to put the text files when I distribute the app?分发应用程序时将文本文件放在哪里?
【发布时间】:2016-08-28 21:28:52
【问题描述】:

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

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

}

【问题讨论】:

    标签: ios swift xcode file app-distribution


    【解决方案1】:

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

    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 的 Build Phases | 的包中。复制捆绑资源。

    【讨论】:

    • 该文件在捆绑包中,但是当我尝试获取长度时,我得到了 nil。 print("length = " + String(data?.length)) //给我nil,我应该如何正确添加到bundle,文件也在项目的目录中(它不仅仅是一个参考)
    • 当我输入完整地址时,长度不再为零
    • 您是否执行了“确保它们包含在 Xcode 的构建阶段 | 复制捆绑资源的捆绑包中”的这部分答案。 ?
    • 是的,当我进入构建阶段,复制捆绑资源时,它会显示 science.txt 文件。我很困惑,我认为它应该可以工作,但它没有,还有什么我可能遗漏的吗?
    • 正如我所提到的,这取决于您使用的 Swift 版本。您使用的是旧版本的 Swift 和 Xcode。一旦您升级到 Xcode 8 并且如果您迁移到 swift 3,那么您的代码将需要更改为我发布的内容。 NSBundle 已重命名为 Bundle,mainBundle 已重命名为 main
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-05
      • 1970-01-01
      相关资源
      最近更新 更多