【发布时间】:2015-04-16 16:25:09
【问题描述】:
我对构建 iOS 应用非常陌生。
我正在尝试创建一个类来接收 udp 多播消息,但我根本无法让它工作...
class Discovery : GCDAsyncUdpSocketDelegate{
var udpSocket:GCDAsyncUdpSocket!;
init() {
udpSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
var e:NSErrorPointer = nil;
//Binding to port
if(!udpSocket.bindToPort(2025, error: e)){
println(e);
return;
}
//Joining multicast group
if(!udpSocket.joinMulticastGroup("239.5.6.7", error: e)){
println(e);
return;
}
//Begin recieve
if(!udpSocket.beginReceiving(e)){
println(e);
return;
}
println("UDP socket was opened!")
}
func udpSocket(sock: GCDAsyncUdpSocket!, didReceiveData data: NSData!, fromAddress address: NSData!, withFilterContext filterContext: AnyObject!) {
println("Got data!");
}
}
谁能看出我哪里出错了?我得到 UDP 套接字已打开消息,但没有收到任何包。我知道它们正在被发送,因为我正在使用wireshark 捕获它们。
发现是从我的视图控制器调用的
class ViewController: UIViewController, CLLocationManagerDelegate {
let peer = Peer(id: NSUUID.new())
let uuid = NSUUID.new()
let discovery:Discovery = Discovery()
let locationManager = CLLocationManager()
let region = CLBeaconRegion(proximityUUID: NSUUID(UUIDString: "8DEEFBB9-F738-4297-8040-96668BB44281"), identifier: "Roximity")
let com = OconCom()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self;
if (CLLocationManager.authorizationStatus() != CLAuthorizationStatus.AuthorizedAlways) {
locationManager.requestAlwaysAuthorization()
}
locationManager.startMonitoringForRegion(region) //Background
locationManager.startRangingBeaconsInRegion(region) //Foreground
}
任何建议都会有所帮助。
【问题讨论】:
-
尝试实现
udpSocketDidClose委托方法以确保您的套接字没有关闭。 -
我不是为什么它起作用,但是当我将代码移动到已经存在的 ViewController 时它起作用了。委托必须是实际运行的视图控制器才能工作吗?
-
委托只需驻留在内存中即可接收回调。也许您还没有初始化
Discovery的实例?如果您发布更多上下文代码,我可以尝试解释得更好。 -
@Ralfonso - 如果发布了我称之为发现的 sn-p。谢谢! :-)
-
我必须承认,即使有附加代码,我乍一看也看不出有什么问题。稍后我会尝试复制它,看看我是否能找出问题所在。有趣的错误!
标签: ios swift gcdasyncudpsocket