簡體   English   中英

異步回調中的遞歸 (Swift)

[英]Recursion in async callback (Swift)

這是一些代碼,它旨在使手機振動(異步),等待此任務完成,然后立即使其再次振動:

func vibrate() {
    AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
    AudioServicesAddSystemSoundCompletion(SystemSoundID(kSystemSoundID_Vibrate), nil, nil, { (soundId, clientData) -> Void in
        self.vibrate()
    }, nil)
}

Xcode 給出以下錯誤:

AC function pointer cannot be formed from a closure that captures context

我如何從這個異步函數內部遞歸?

我正在努力為您的問題找到解決方案,但偶然發現了這個線程: https : //forums.swift.org/t/ac-function-pointer-cannot-be-formed-from-a-local-function -that-c​​aptures-context-on-swift-package/9388/6

我確實將vibrate()方法封裝到一個新結構中,如下所示:

import AudioToolbox
import CoreAudioKit

struct Vibrator {
    static func vibrate() {
        AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
        AudioServicesAddSystemSoundCompletion(SystemSoundID(kSystemSoundID_Vibrate), nil, nil, { (soundId, clientData) in
            Vibrator.vibrate()
        }, nil)
    }
}

當然像這樣稱呼它: Vibrator.vibrate() 瞧!

我希望這有幫助!

您也可以使用這種方式調用類中的任何函數;

AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) 
let myData = unsafeBitCast(self, to: UnsafeMutableRawPointer.self) 
AudioServicesAddSystemSoundCompletion(SystemSoundID(kSystemSoundID_Vibrate), 
CFRunLoopGetMain(), nil ,{ (soundId, clientData) in 
let currentSelf = unsafeBitCast(clientData, to: YOUR_CLASS_NAME.self) 
currentSelf.vibrate() // call any funcation from current Controller
}, myData)

這是我最終找到的解決方案。 事實證明,有一個內置函數AudioServicesPlaySystemSoundWithCompletion ,它將回調作為參數:

func vibrate() {
    AudioServicesPlaySystemSoundWithCompletion(SystemSoundID(kSystemSoundID_Vibrate)) {
        self.vibrate()
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM