小编典典

Swift:将数据传递到捕获上下文的闭包

swift

我正在尝试在互联网连接恢复且updateOnConnection变量为true 时调用一个函数。这是我的代码:

func checkForConnection() {
    let host = "reddit.com"
    var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
    let reachability = SCNetworkReachabilityCreateWithName(nil, host)!

    SCNetworkReachabilitySetCallback(reachability, { (_, flags, _) in
        if flags.rawValue == 0 { //internet is not connected

        } else { //internet became connected
            if self.updateOnConnection {
                self.refreshWallpaper()
            }
        }
    }, &context)

    SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetMain(), kCFRunLoopCommonModes)
}

我的问题是这些行:

        if self.updateOnConnection {
            self.refreshWallpaper()
        }

导致错误:“ A C function pointer cannot be formed from a closure that captures context

我不确定如何检查状态updateOnConnection并调用refreshWallpaper()监视Internet连接变化的闭包。如何解决此问题,或者我应该使用完全不同的解决方法?


阅读 458

收藏
2020-07-07

共1个答案

小编典典

类似于如何将实例方法用作仅使用func或立即数闭包的函数的回调中一样,您必须转换
self为void指针,将其存储在上下文中,然后将其转换回闭包中的对象指针:

func checkForConnection() {

    let host = "reddit.com"
    var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
    context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque())

    let reachability = SCNetworkReachabilityCreateWithName(nil, host)!

    SCNetworkReachabilitySetCallback(reachability, { (_, flags, info) in
        if flags.rawValue == 0 { //internet is not connected

        } else { //internet became connected
            let mySelf = Unmanaged<ViewController>.fromOpaque(COpaquePointer(info)).takeUnretainedValue()

            if mySelf.updateOnConnection {
                mySelf.refreshWallpaper()
            }
        }
        }, &context)

    SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetMain(), kCFRunLoopCommonModes)
}

备注: if flags.rawValue == 0可以表示得稍微优雅一些if flags.isEmpty,但是您 实际上
应该检查的是if flags.contains(.Reachable)


Swift 3的更新(Xcode 8 beta 6):

func checkForConnection() {

    let host = "reddit.com"
    var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
    context.info = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())

    let reachability = SCNetworkReachabilityCreateWithName(nil, host)!

    SCNetworkReachabilitySetCallback(reachability, { (_, flags, info) in
        if let info = info {
            if flags.rawValue == 0 { //internet is not connected

            } else { //internet became connected
                let mySelf = Unmanaged<ViewController>.fromOpaque(info).takeUnretainedValue()
                // ...
            }
        }
    }, &context)

    SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetMain(), CFRunLoopMode.commonModes.rawValue)
}
2020-07-07