0

ファイルがドキュメント フォルダに保存されたら、viewController のビューをリロード/更新することは可能ですか? はいの場合は、これを達成する方法を親切に提案してください。

ファイルをAppDelegateに保存しようとしていますが、XML 解析が含まれているため、ビューが読み込まれたときにのみ保存されます。これは、ファイルの内容を表示することになっているビューです。ただし、ファイルが保存される前にロードされるため、ビューには何も表示されません。

このクエリは、このリンクの私の質問に関連しています

ここでもう一度コードを共有しましょうか。

4

1 に答える 1

1

プロセスをご案内できます。実装する必要があるのは次のとおりです。

  1. ファイルがストレージに書き込まれると、Notificationスルーを投稿できますNotificationCenter。(さらに、投稿する直前にファイルの存在を確認できますNotification)。
  2. あなたの(おそらく内部)でそれをobserver聞くためのを追加します。NotificationNotificationCenterViewControllerviewDidLoad()
  3. を追加するときは、通知が発生したときに呼び出される (メソッド) をobserver指定する必要があります。selectorしたがって、メソッドを追加してselector、addObserver の として提供します。
  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 に答える