保存文件后如何重新加载或更新 viewController 的视图
How to reload or update a viewController's view once a file is saved
一旦文件保存在文档文件夹中,是否可以reload/update viewController 的视图?
如果是,请建议如何完成此操作。
我正在尝试在 AppDelegate 中保存一个文件,但由于它涉及 XML 解析,因此只有在加载视图时才会保存该文件。这是应该显示文件内容的视图。但是由于它在文件保存之前加载,因此视图不显示任何内容。
此查询与我在此 link
的问题相关
我要在这里再分享一次代码吗?
我可以指导您完成整个过程。你需要实现的是:
- 当您的文件写入存储后,您可以 post 到
Notification
到 NotificationCenter
。 (此外,您可以在 posting Notification
之前立即检查文件是否存在)。
- 在您的
ViewController
(可能在 viewDidLoad()
内)添加一个 observer
用于收听 Notification
到 NotificationCenter
。
- 当您添加
observer
时,您需要指定一个 selector
(方法),该方法将在通知发生时调用。所以添加一个方法并将其作为 selector
提供给 addObserver.
- 在该方法中执行所需的操作,并在方法的最后标记您的
view
脏。通常用 self.view.setNeedsDisplay()
完成。这将完成 reloading/updating 部分。
EDIT: added some code example
这里是post相关代码。关注代码中的注释。
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)")
}
}
}
一旦文件保存在文档文件夹中,是否可以reload/update viewController 的视图? 如果是,请建议如何完成此操作。
我正在尝试在 AppDelegate 中保存一个文件,但由于它涉及 XML 解析,因此只有在加载视图时才会保存该文件。这是应该显示文件内容的视图。但是由于它在文件保存之前加载,因此视图不显示任何内容。
此查询与我在此 link
的问题相关我要在这里再分享一次代码吗?
我可以指导您完成整个过程。你需要实现的是:
- 当您的文件写入存储后,您可以 post 到
Notification
到NotificationCenter
。 (此外,您可以在 postingNotification
之前立即检查文件是否存在)。 - 在您的
ViewController
(可能在viewDidLoad()
内)添加一个observer
用于收听Notification
到NotificationCenter
。 - 当您添加
observer
时,您需要指定一个selector
(方法),该方法将在通知发生时调用。所以添加一个方法并将其作为selector
提供给 addObserver. - 在该方法中执行所需的操作,并在方法的最后标记您的
view
脏。通常用self.view.setNeedsDisplay()
完成。这将完成 reloading/updating 部分。
EDIT: added some code example
这里是post相关代码。关注代码中的注释。
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)")
}
}
}