Home > front end >  How to use Dispatch?
How to use Dispatch?

Time:02-15

The compiler said,

Cannot pass function of type '() async -> Void' to parameter expecting synchronous function type

enter image description here

This is the problem code:

    DispatchQueue.global().async {
   
    
    await CreateFolder()
    
    do {
        let FilePath = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        let FileName = UUID().uuidString
        try! Image.pngData()!.write(to: FilePath.appendingPathComponent("Images").appendingPathComponent("\(FileName).png"))
    } catch {
        Prompt(error.localizedDescription)
    }
    }

CodePudding user response:

Async methods call in a function that does not support concurrency. You can use Task.init

Task.init {
            do {
                   _ = try await CreateFolder()
                   let FilePath = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
                           let FileName = UUID().uuidString
                           try! Image.pngData()!.write(to: FilePath.appendingPathComponent("Images").appendingPathComponent("\(FileName).png"))
               } catch {
                   Prompt(error.localizedDescription)
               }
           }

CodePudding user response:

Remove await from DispatchQueue closure.

Fixed:

    DispatchQueue.global().async {
   
    
    CreateFolder()
    
    do {
        let FilePath = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        let FileName = UUID().uuidString
        try! Image.pngData()!.write(to: FilePath.appendingPathComponent("Images").appendingPathComponent("\(FileName).png"))
    } catch {
        Prompt(error.localizedDescription)
    }
    }
  • Related