Swift 3 - CFHostScheduleWithRunLoop crash

时间秒杀一切 提交于 2019-12-25 09:10:09

问题


I am doing a reverse DNS in Swift, my previous code on Swift 2.2 was working fine, also I have implemented it in Objective-C and it works to. However I am not able to make it works in Swift 3.0

Swift 2.2

//: Let's set up the `sockaddr_in` C structure using the initializer.
var sin = sockaddr_in(
    sin_len: UInt8(sizeof(sockaddr_in)),
    sin_family: sa_family_t(AF_INET),
    sin_port: in_port_t(0),
    sin_addr: in_addr(s_addr: inet_addr(ip)),
    sin_zero: (0,0,0,0,0,0,0,0)
)

//: Now convert the structure into a `CFData` object.
let data = withUnsafePointer(&sin) { ptr in
    CFDataCreate(kCFAllocatorDefault, UnsafePointer(ptr), sizeof(sockaddr_in))
}

//: Create the `CFHostRef` with the `CFData` object and store the retained value for later use.
let host = CFHostCreateWithAddress(kCFAllocatorDefault, data).takeRetainedValue()

//: Now schedule the runloop for the host.
CFHostScheduleWithRunLoop(host!, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode)

var error = CFStreamError()

//: Start the info resolution.
CFHostStartInfoResolution(host!, .Names, &error)

Swift 3.0

//: Let's set up the `sockaddr_in` C structure using the initializer.
var sin = sockaddr_in(
    sin_len: UInt8(sizeof(sockaddr_in)),
    sin_family: sa_family_t(AF_INET),
    sin_port: in_port_t(0),
    sin_addr: in_addr(s_addr: inet_addr(ip)),
    sin_zero: (0,0,0,0,0,0,0,0)
)

//: Now convert the structure into a `CFData` object.
let data = NSData(bytes: &sin, length: MemoryLayout<sockaddr_in>.size) as CFData

//: Create the `CFHostRef` with the `CFData` object and store the retained value for later use.
let host = CFHostCreateWithAddress(kCFAllocatorDefault, data).takeRetainedValue()

//: Now schedule the runloop for the host.
CFHostScheduleWithRunLoop(host!, CFRunLoopGetCurrent(), CFRunLoopMode.defaultMode as! CFString)

var error = CFStreamError()

//: Start the info resolution.
CFHostStartInfoResolution(host!, .Names, &error)

When I ran this code it it crash at

CFHostScheduleWithRunLoop

any idea?


回答1:


Try to replace:

CFRunLoopMode.defaultMode as! CFString

with:

CFRunLoopMode.defaultMode!.rawValue


来源:https://stackoverflow.com/questions/39476628/swift-3-cfhostschedulewithrunloop-crash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!