I am perplexed as to how to use async await. In the following example, I don't use GCD or performSelector(inBackground:with:). The view controller is NSViewController, but it doesn't make any difference if it's NSViewController or UIViewController.
import Cocoa
class ViewController: NSViewController {
func startWriteImages() {
Task{
let bool = await startWriteImagesNext()
if bool {
print("I'm done!")
}
}
}
func startWriteImagesNext() async -> Bool {
// pictures is a path to a folder in the sandbox folder
// appDelegate.defaultFileManager is a variable pointing to FileManager.default in AppDelegate
let pictURL = URL(fileURLWithPath: pictures)
if let filePaths = try? self.appDelegate.defaultFileManager.contentsOfDirectory(atPath: pictURL.path) {
for file in filePaths {
let fileURL = pictURL.appending(component: file)
if self.appDelegate.defaultFileManager.fileExists(atPath: fileURL.path) {
let newURL = self.folderURL.appending(component: file)
do {
try self.appDelegate.defaultFileManager.copyItem(at: fileURL, to: newURL)
} catch {
print("Ugghhh...")
}
}
}
return true
}
return false
}
func startWriteImagesNext2() async -> Bool {
let pictURL = URL(fileURLWithPath: pictures)
if let filePaths = try? self.appDelegate.defaultFileManager.contentsOfDirectory(atPath: pictURL.path) {
DispatchQueue.global().async() {
for file in filePaths {
let fileURL = pictURL.appending(component: file)
if self.appDelegate.defaultFileManager.fileExists(atPath: fileURL.path) {
let newURL = self.folderURL.appending(component: file)
do {
try self.appDelegate.defaultFileManager.copyItem(at: fileURL, to: newURL)
} catch {
print("Ugghhh...")
}
}
}
}
return true
}
return false
}
}
In the code above, I'm saving each file in the folder to user-selected folder (self.folderURL). And the application will execute the print guy only when work is done. Since it's heavy-duty work, I want to use CCD or performSelector(inBackground:with:). If I use the former (startWriteImagesNext2), the application will execute the print guy right at the beginning. I suppose I cannot use GCD with async. So how can I perform heavy-duty work? Muchos thankos.