我在分发应用时放置文本文件的位置?

时间:2016-08-28 21:28:53

标签: ios swift xcode file app-distribution

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

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

}

enter image description here

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

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