0

一旦文件保存在文档文件夹中,是否可以重新加载/更新 viewController 的视图?如果是,请建议如何完成此操作。

我正在尝试将文件保存在AppDelegate中,但由于它涉及 XML 解析,因此仅在加载视图时才保存。这是应该显示文件内容的视图。但是由于它在保存文件之前被加载,因此视图不会显示任何内容。

此查询与我在此链接上的问题有关

我要在这里再次分享代码吗?

4

1 回答 1

1

我可以指导你完成整个过程。你需要实现的是:

  1. 当您的文件被写入存储时,您可以Notification通过NotificationCenter. (此外,您可以在发布之前立即检查文件是否存在Notification)。
  2. 在你的(也许在里面)中添加一个observer用于收听的NotificationNotificationCenterViewControllerviewDidLoad()
  3. 添加时,observer您需要指定selector在通知发生时将调用的(方法)。所以添加一个方法并将其作为selectoraddObserver 提供。
  4. 在该方法中执行您所需的操作,并在该方法的最后标记您的view脏。它通常与self.view.setNeedsDisplay(). 这将完成重新加载/更新部分。

编辑:添加了一些代码示例

在这里,我发布了相关代码。关注代码中的注释。

AppDelegate.swift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    postNotificationAfterFileSave()
    return true
}

func postNotificationAfterFileSave() {
    // do your job with your custom class's method for saving
    // you should get a filepath back
    CustomXMLParser().parseAndSave { (filePath) in
        if FileManager.default.fileExists(atPath: filePath) {
            // if the file exists, post Notification
            NotificationCenter.default.post(name: Notification.Name("FileWrittenCompletion"), object: nil)
        }
    }
}

ViewController.swift

@IBOutlet weak var myLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    // add an observer for your Notification and specify a selector that will be called when Notification is got
    NotificationCenter.default.addObserver(self, selector: #selector(updateUI), name: Notification.Name("FileWrittenCompletion"), object: nil)
    myLabel.text = "File is being saved"
}

@objc func updateUI() {
    // this method will be called when Notification happens
    // change your UI objects according to your needs
    myLabel.textColor = #colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1)
    myLabel.text = "File is saved successfully"
    // Finally mark your view `dirty` that will do the reloading task of the UI
    self.view.setNeedsDisplay()
}

CustomXMLParser.swift

func parseAndSave(completion: @escaping (String)-> Void ) {
    let when = DispatchTime.now() + 10
    DispatchQueue.global().asyncAfter(deadline: when) {
        let string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
        // get the document directory
        let fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("myFile").appendingPathExtension("txt")

        do {
            // write to filepath
            try string.write(to: fileURL!, atomically: true, encoding: .utf8)

            DispatchQueue.main.async {
                // return the filePath through completion block
                completion((fileURL?.path)!)
            }

        } catch {
            print("\(error.localizedDescription)")
        }

    }
}
于 2017-06-15T08:32:18.447 回答