Swift 中 callback 调用

Swift closures and functions are decidedly not C functions. They exist in a weird halfway state between C++ members and Objective-C blocks, so you'll have to move any callbacks into an Objective-C file and take a block or have some other means of calling back to Swift. For example you might have your own version of the relevant AVFoundation functions take a block:

void audioQueueHandleBuffer(void *ctx, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer) {
    NSCAssert(ctx != NULL, @"Cannot execute NULL context block.");

    void(^block)(AudioQueueRef, AudioQueueBufferRef) = (__bridge void(^)(AudioQueueRef, AudioQueueBufferRef))ctx;

    return block(inAQ, inBuffer);
}

OSStatus CFIAudioQueueNewOutput(AudioStreamBasicDescription *desc, void(^callback)(AudioQueueRef, AudioQueueBufferRef), AudioQueueRef *queue) {
    return AudioQueueNewOutput(desc, audioQueueHandleBuffer, (__bridge_retained void *)([callback copy]), nil, nil, 0, queue);
}

Then just pass your function through like you would expect in Swift.

class AudioQueue {

    var desc : AudioStreamBasicDescription
    var queue : AudioQueueRef

    func audioQueueHandleBuffer(inAQ : AudioQueueRef, inBuffer : AudioQueueBufferRef) {
            // do stuff
    }

    func initialize() {
        var err = CFIAudioQueueNewOutput(&desc, audioQueueHandleBuffer, &queue)

        // ...
    }
}

It's an incredibly painful workaround for a problem that you shouldn't be trying to express in Swift. Code that must manipulate pointers, especially function pointers, is best left in a C or Objective-C file. Otherwise, you're just fighting an unnecessary battle against the language -especially because it has such great support for C and Objective-C interoperability.



func forwardGetRequestToServer(url: NSURL, completion: (result: NSDictionary) -> Void) {
    let request = NSMutableURLRequest(URL: url)
    request.HTTPMethod = "GET"
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in
        if error != nil {
            print("error=\(error)")
            return
        }
        do {

            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! NSDictionary
            completion(result: json)

        } catch {
            print("error serializing JSON: \(error)")

        }

        }

    task.resume() }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值