How to access file included in app bundle in Swift?

后端 未结 7 1908
灰色年华
灰色年华 2020-11-30 05:46

I know there are a few questions pertaining to this, but they\'re in Objective-C.

How can I access a .txt file included in my app using Swift on

7条回答
  •  野性不改
    2020-11-30 06:03

    Simply by searching in the app bundle for the resource

    var filePath = NSBundle.mainBundle().URLForResource("file", withExtension: "txt")
    

    However you can't write to it because it is in the app resources directory and you have to create it in the document directory to write to it

    var documentsDirectory: NSURL?
    var fileURL: NSURL?
    
    documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last!
    fileURL = documentsDirectory!.URLByAppendingPathComponent("file.txt")
    
    if (fileURL!.checkResourceIsReachableAndReturnError(nil)) {
        print("file exist")
    }else{
        print("file doesnt exist")
        NSData().writeToURL(fileURL!,atomically:true)
    }
    

    now you can access it from fileURL

    EDIT - 28 August 2018

    This is how to do it in Swift 4.2

    var filePath = Bundle.main.url(forResource: "file", withExtension: "txt")
    

    To create it in the document directory

    if let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last {
       let fileURL = documentsDirectory.appendingPathComponent("file.txt")
       do {
           if try fileURL.checkResourceIsReachable() {
               print("file exist")
           } else {
               print("file doesnt exist")
               do {
                try Data().write(to: fileURL)
               } catch {
                   print("an error happened while creating the file")
               }
           }
       } catch {
           print("an error happened while checking for the file")
       }
    }
    

提交回复
热议问题