Как скопировать файл пакета html в каталог документов в iOS Swift? - PullRequest
0 голосов
/ 18 февраля 2020

Я пытался сохранить локальный индекс. html файл в каталог документов, но он не сохраняется в локальный каталог документов.

вот моя структура папок:

sampleHtml.xcodeproj
---->sampleHtml
-------->Web_Assets
------------> index.html
---->ViewController.swift

Вот код для сохранения и проверки пути к файлу, которого не существует, если путь существует, перезапишите его, либо скопируйте новый.

func saveHtmlDoc(){
    let filemgr = FileManager.default
    let docURL = filemgr.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let destPath = docURL.path+"/www/"
    print("des path", destPath)
    let sourcePath = Bundle.main.resourceURL!.appendingPathComponent("Web_Assets").path
    print("sourc", sourcePath.appending("/index.html"))

      //COPY Web_Assets content from Bundle to Documents/www
      do {
          try filemgr.removeItem(atPath: destPath)
      } catch {
          print("Error: \(error.localizedDescription)")
      }
      do {
          try filemgr.copyItem(atPath:  sourcePath + "/", toPath: destPath)
      } catch {
          print("Error: \(error.localizedDescription)")
      }

}

Моя проблема заключается в том, как сохранить индекс. html файл в каталоге документов и проверьте, что пути к файлу не существует, если существует, перезапишите его или скопируйте новый.

Любая помощь очень ценит это ...

Ответы [ 2 ]

1 голос
/ 18 февраля 2020

Я пытаюсь протестировать приведенный ниже код, он работает хорошо. Прежде чем добавить файл, вам нужно сначала создать папку.

func saveHtmlDoc() {
    let filemgr = FileManager.default
    let docURL = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
    let destPath = URL(string:docURL)?.appendingPathComponent("www")

    guard let newDestPath = destPath, let sourcePath = Bundle.main.path(forResource: "image", ofType: ".png"), let fullDestPath = NSURL(fileURLWithPath: newDestPath.absoluteString).appendingPathComponent("image.png") else { return  }

    //CREATE FOLDER
    if !filemgr.fileExists(atPath: newDestPath.path) {
        do {
            try filemgr.createDirectory(atPath: newDestPath.path, withIntermediateDirectories: true, attributes: nil)
        } catch {
            print(error.localizedDescription);
        }
    }
    else {
        print("Folder is exist")
    }

    if filemgr.fileExists(atPath: fullDestPath.path) {
        print("File is exist in \(fullDestPath.path)")
    }
    else {
        do {
            try filemgr.copyItem(atPath:  sourcePath, toPath: fullDestPath.path)
        } catch {
            print("Error: \(error.localizedDescription)")
        }
    }
}
1 голос
/ 18 февраля 2020

Я только что сделал этот код в тестовом проекте, который работает.

Вы должны убедиться, что вы выполняете проверки по пути, и убедиться, что ваш файл HTML находится на этапе создания ресурсов копирования

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        moveHtmlFile()
    }

    private func moveHtmlFile() {
        let fileManager = FileManager.default
        let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
        guard let sourcePath = Bundle.main.path(forResource: "index", ofType: "html") else {
            return
        }

        if fileManager.fileExists(atPath: sourcePath) {
            let sourceUrl = URL(fileURLWithPath: sourcePath)
            try? fileManager.createDirectory(atPath: documentsDirectory.appendingPathComponent("www").path,
                                             withIntermediateDirectories: false,
                                             attributes: nil)
            let destination = documentsDirectory.appendingPathComponent("www/index.html", isDirectory: false)
            try? fileManager.copyItem(at: sourceUrl, to: destination)

            if fileManager.fileExists(atPath: destination.path) {
                print("file copied")
            } else {
                print("file copy failed")
            }
        }
    }

}

Результат:

enter image description here

...