Swift: How to copy files from app bundle to Documents folder when app runs for first time












-5















There are all sorts of sample code & questions on SO dealing with how to programmatically copy files in Obj-C from the app bundle to the application's sandboxed Documents folder (e.g. here, here, and here) when the application runs for the first time.



How do you do this in Swift?










share|improve this question




















  • 5





    There is no way to copy files to the Documents folder at build time in any language. It needs to be done at runtime, not build time. And if you have code in Objective-C, then why can't you translate the code to Swift? It's the same APIs.

    – rmaddy
    Jan 2 at 21:50











  • sorry, I'm not using the correct terminology. I was thinking of "build time" as the first time the app is installed -- but you're right; that's still run time. I have rephrased the question.

    – MMac
    Jan 2 at 22:32
















-5















There are all sorts of sample code & questions on SO dealing with how to programmatically copy files in Obj-C from the app bundle to the application's sandboxed Documents folder (e.g. here, here, and here) when the application runs for the first time.



How do you do this in Swift?










share|improve this question




















  • 5





    There is no way to copy files to the Documents folder at build time in any language. It needs to be done at runtime, not build time. And if you have code in Objective-C, then why can't you translate the code to Swift? It's the same APIs.

    – rmaddy
    Jan 2 at 21:50











  • sorry, I'm not using the correct terminology. I was thinking of "build time" as the first time the app is installed -- but you're right; that's still run time. I have rephrased the question.

    – MMac
    Jan 2 at 22:32














-5












-5








-5








There are all sorts of sample code & questions on SO dealing with how to programmatically copy files in Obj-C from the app bundle to the application's sandboxed Documents folder (e.g. here, here, and here) when the application runs for the first time.



How do you do this in Swift?










share|improve this question
















There are all sorts of sample code & questions on SO dealing with how to programmatically copy files in Obj-C from the app bundle to the application's sandboxed Documents folder (e.g. here, here, and here) when the application runs for the first time.



How do you do this in Swift?







ios swift






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 8 at 15:48







MMac

















asked Jan 2 at 21:04









MMacMMac

748




748








  • 5





    There is no way to copy files to the Documents folder at build time in any language. It needs to be done at runtime, not build time. And if you have code in Objective-C, then why can't you translate the code to Swift? It's the same APIs.

    – rmaddy
    Jan 2 at 21:50











  • sorry, I'm not using the correct terminology. I was thinking of "build time" as the first time the app is installed -- but you're right; that's still run time. I have rephrased the question.

    – MMac
    Jan 2 at 22:32














  • 5





    There is no way to copy files to the Documents folder at build time in any language. It needs to be done at runtime, not build time. And if you have code in Objective-C, then why can't you translate the code to Swift? It's the same APIs.

    – rmaddy
    Jan 2 at 21:50











  • sorry, I'm not using the correct terminology. I was thinking of "build time" as the first time the app is installed -- but you're right; that's still run time. I have rephrased the question.

    – MMac
    Jan 2 at 22:32








5




5





There is no way to copy files to the Documents folder at build time in any language. It needs to be done at runtime, not build time. And if you have code in Objective-C, then why can't you translate the code to Swift? It's the same APIs.

– rmaddy
Jan 2 at 21:50





There is no way to copy files to the Documents folder at build time in any language. It needs to be done at runtime, not build time. And if you have code in Objective-C, then why can't you translate the code to Swift? It's the same APIs.

– rmaddy
Jan 2 at 21:50













sorry, I'm not using the correct terminology. I was thinking of "build time" as the first time the app is installed -- but you're right; that's still run time. I have rephrased the question.

– MMac
Jan 2 at 22:32





sorry, I'm not using the correct terminology. I was thinking of "build time" as the first time the app is installed -- but you're right; that's still run time. I have rephrased the question.

– MMac
Jan 2 at 22:32












2 Answers
2






active

oldest

votes


















0














You could use FileManager API:



Here's example with a function that copies all files with specified extension:



func copyFilesFromBundleToDocumentsFolderWith(fileExtension: String) {
if let resPath = Bundle.main.resourcePath {
do {
let dirContents = try FileManager.default.contentsOfDirectory(atPath: resPath)
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let filteredFiles = dirContents.filter{ $0.contains(fileExtension)}
for fileName in filteredFiles {
if let documentsURL = documentsURL {
let sourceURL = Bundle.main.bundleURL.appendingPathComponent(fileName)
let destURL = documentsURL.appendingPathComponent(fileName)
do { try FileManager.default.copyItem(at: sourceURL, to: destURL) } catch { }
}
}
} catch { }
}
}


Usage:



copyFilesFromBundleToDocumentsFolderWith(fileExtension: ".txt")





share|improve this answer


























  • I didn't ask for the extra detail about only copying files of a particular extension, but that is super helpful and most definitely was the next issue I was going to have to solve. Despite the community not finding the question helpful, your answer IS helpful to me and I appreciate the time you put in. Thank you!

    – MMac
    Jan 3 at 13:16



















-2














For Swift 4.2:



Assuming the file in your App Bundle is called Some File.txt



In ViewDidLoad, add:



let docName = "Some File"
let docExt = "txt"
copyFileToDocumentsFolder(nameForFile: docName, extForFile: docExt)


and then create a function as follows:



func copyFileToDocumentsFolder(nameForFile: String, extForFile: String) {

let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let destURL = documentsURL!.appendingPathComponent(nameForFile).appendingPathExtension(extForFile)
guard let sourceURL = Bundle.main.url(forResource: nameForFile, withExtension: extForFile)
else {
print("Source File not found.")
return
}
let fileManager = FileManager.default
do {
try fileManager.copyItem(at: sourceURL, to: destURL)
} catch {
print("Unable to copy file")
}
}





share|improve this answer


























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54013155%2fswift-how-to-copy-files-from-app-bundle-to-documents-folder-when-app-runs-for-f%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    You could use FileManager API:



    Here's example with a function that copies all files with specified extension:



    func copyFilesFromBundleToDocumentsFolderWith(fileExtension: String) {
    if let resPath = Bundle.main.resourcePath {
    do {
    let dirContents = try FileManager.default.contentsOfDirectory(atPath: resPath)
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
    let filteredFiles = dirContents.filter{ $0.contains(fileExtension)}
    for fileName in filteredFiles {
    if let documentsURL = documentsURL {
    let sourceURL = Bundle.main.bundleURL.appendingPathComponent(fileName)
    let destURL = documentsURL.appendingPathComponent(fileName)
    do { try FileManager.default.copyItem(at: sourceURL, to: destURL) } catch { }
    }
    }
    } catch { }
    }
    }


    Usage:



    copyFilesFromBundleToDocumentsFolderWith(fileExtension: ".txt")





    share|improve this answer


























    • I didn't ask for the extra detail about only copying files of a particular extension, but that is super helpful and most definitely was the next issue I was going to have to solve. Despite the community not finding the question helpful, your answer IS helpful to me and I appreciate the time you put in. Thank you!

      – MMac
      Jan 3 at 13:16
















    0














    You could use FileManager API:



    Here's example with a function that copies all files with specified extension:



    func copyFilesFromBundleToDocumentsFolderWith(fileExtension: String) {
    if let resPath = Bundle.main.resourcePath {
    do {
    let dirContents = try FileManager.default.contentsOfDirectory(atPath: resPath)
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
    let filteredFiles = dirContents.filter{ $0.contains(fileExtension)}
    for fileName in filteredFiles {
    if let documentsURL = documentsURL {
    let sourceURL = Bundle.main.bundleURL.appendingPathComponent(fileName)
    let destURL = documentsURL.appendingPathComponent(fileName)
    do { try FileManager.default.copyItem(at: sourceURL, to: destURL) } catch { }
    }
    }
    } catch { }
    }
    }


    Usage:



    copyFilesFromBundleToDocumentsFolderWith(fileExtension: ".txt")





    share|improve this answer


























    • I didn't ask for the extra detail about only copying files of a particular extension, but that is super helpful and most definitely was the next issue I was going to have to solve. Despite the community not finding the question helpful, your answer IS helpful to me and I appreciate the time you put in. Thank you!

      – MMac
      Jan 3 at 13:16














    0












    0








    0







    You could use FileManager API:



    Here's example with a function that copies all files with specified extension:



    func copyFilesFromBundleToDocumentsFolderWith(fileExtension: String) {
    if let resPath = Bundle.main.resourcePath {
    do {
    let dirContents = try FileManager.default.contentsOfDirectory(atPath: resPath)
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
    let filteredFiles = dirContents.filter{ $0.contains(fileExtension)}
    for fileName in filteredFiles {
    if let documentsURL = documentsURL {
    let sourceURL = Bundle.main.bundleURL.appendingPathComponent(fileName)
    let destURL = documentsURL.appendingPathComponent(fileName)
    do { try FileManager.default.copyItem(at: sourceURL, to: destURL) } catch { }
    }
    }
    } catch { }
    }
    }


    Usage:



    copyFilesFromBundleToDocumentsFolderWith(fileExtension: ".txt")





    share|improve this answer















    You could use FileManager API:



    Here's example with a function that copies all files with specified extension:



    func copyFilesFromBundleToDocumentsFolderWith(fileExtension: String) {
    if let resPath = Bundle.main.resourcePath {
    do {
    let dirContents = try FileManager.default.contentsOfDirectory(atPath: resPath)
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
    let filteredFiles = dirContents.filter{ $0.contains(fileExtension)}
    for fileName in filteredFiles {
    if let documentsURL = documentsURL {
    let sourceURL = Bundle.main.bundleURL.appendingPathComponent(fileName)
    let destURL = documentsURL.appendingPathComponent(fileName)
    do { try FileManager.default.copyItem(at: sourceURL, to: destURL) } catch { }
    }
    }
    } catch { }
    }
    }


    Usage:



    copyFilesFromBundleToDocumentsFolderWith(fileExtension: ".txt")






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jan 3 at 9:22

























    answered Jan 2 at 21:13









    BrooketaBrooketa

    778




    778













    • I didn't ask for the extra detail about only copying files of a particular extension, but that is super helpful and most definitely was the next issue I was going to have to solve. Despite the community not finding the question helpful, your answer IS helpful to me and I appreciate the time you put in. Thank you!

      – MMac
      Jan 3 at 13:16



















    • I didn't ask for the extra detail about only copying files of a particular extension, but that is super helpful and most definitely was the next issue I was going to have to solve. Despite the community not finding the question helpful, your answer IS helpful to me and I appreciate the time you put in. Thank you!

      – MMac
      Jan 3 at 13:16

















    I didn't ask for the extra detail about only copying files of a particular extension, but that is super helpful and most definitely was the next issue I was going to have to solve. Despite the community not finding the question helpful, your answer IS helpful to me and I appreciate the time you put in. Thank you!

    – MMac
    Jan 3 at 13:16





    I didn't ask for the extra detail about only copying files of a particular extension, but that is super helpful and most definitely was the next issue I was going to have to solve. Despite the community not finding the question helpful, your answer IS helpful to me and I appreciate the time you put in. Thank you!

    – MMac
    Jan 3 at 13:16













    -2














    For Swift 4.2:



    Assuming the file in your App Bundle is called Some File.txt



    In ViewDidLoad, add:



    let docName = "Some File"
    let docExt = "txt"
    copyFileToDocumentsFolder(nameForFile: docName, extForFile: docExt)


    and then create a function as follows:



    func copyFileToDocumentsFolder(nameForFile: String, extForFile: String) {

    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
    let destURL = documentsURL!.appendingPathComponent(nameForFile).appendingPathExtension(extForFile)
    guard let sourceURL = Bundle.main.url(forResource: nameForFile, withExtension: extForFile)
    else {
    print("Source File not found.")
    return
    }
    let fileManager = FileManager.default
    do {
    try fileManager.copyItem(at: sourceURL, to: destURL)
    } catch {
    print("Unable to copy file")
    }
    }





    share|improve this answer






























      -2














      For Swift 4.2:



      Assuming the file in your App Bundle is called Some File.txt



      In ViewDidLoad, add:



      let docName = "Some File"
      let docExt = "txt"
      copyFileToDocumentsFolder(nameForFile: docName, extForFile: docExt)


      and then create a function as follows:



      func copyFileToDocumentsFolder(nameForFile: String, extForFile: String) {

      let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
      let destURL = documentsURL!.appendingPathComponent(nameForFile).appendingPathExtension(extForFile)
      guard let sourceURL = Bundle.main.url(forResource: nameForFile, withExtension: extForFile)
      else {
      print("Source File not found.")
      return
      }
      let fileManager = FileManager.default
      do {
      try fileManager.copyItem(at: sourceURL, to: destURL)
      } catch {
      print("Unable to copy file")
      }
      }





      share|improve this answer




























        -2












        -2








        -2







        For Swift 4.2:



        Assuming the file in your App Bundle is called Some File.txt



        In ViewDidLoad, add:



        let docName = "Some File"
        let docExt = "txt"
        copyFileToDocumentsFolder(nameForFile: docName, extForFile: docExt)


        and then create a function as follows:



        func copyFileToDocumentsFolder(nameForFile: String, extForFile: String) {

        let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
        let destURL = documentsURL!.appendingPathComponent(nameForFile).appendingPathExtension(extForFile)
        guard let sourceURL = Bundle.main.url(forResource: nameForFile, withExtension: extForFile)
        else {
        print("Source File not found.")
        return
        }
        let fileManager = FileManager.default
        do {
        try fileManager.copyItem(at: sourceURL, to: destURL)
        } catch {
        print("Unable to copy file")
        }
        }





        share|improve this answer















        For Swift 4.2:



        Assuming the file in your App Bundle is called Some File.txt



        In ViewDidLoad, add:



        let docName = "Some File"
        let docExt = "txt"
        copyFileToDocumentsFolder(nameForFile: docName, extForFile: docExt)


        and then create a function as follows:



        func copyFileToDocumentsFolder(nameForFile: String, extForFile: String) {

        let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
        let destURL = documentsURL!.appendingPathComponent(nameForFile).appendingPathExtension(extForFile)
        guard let sourceURL = Bundle.main.url(forResource: nameForFile, withExtension: extForFile)
        else {
        print("Source File not found.")
        return
        }
        let fileManager = FileManager.default
        do {
        try fileManager.copyItem(at: sourceURL, to: destURL)
        } catch {
        print("Unable to copy file")
        }
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jan 3 at 2:29

























        answered Jan 3 at 2:14









        MMacMMac

        748




        748






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54013155%2fswift-how-to-copy-files-from-app-bundle-to-documents-folder-when-app-runs-for-f%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            MongoDB - Not Authorized To Execute Command

            How to fix TextFormField cause rebuild widget in Flutter

            in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith