一直关注本教程:
http://www.appcoda.com/intro-multipeer-connectivity-framework-ios-programming/
但是一直在转换它在Swift中工作。然而,已经取消了以下内容:
-(void)peerDidChangeStateWithNotification:(NSNotification *)notification
{
MCPeerID *peerID = [[notification userInfo] objectForKey:@"peerID"];
NSString *peerDisplayName = peerID.displayName;
MCSessionState state = [[[notification userInfo] objectForKey:@"state"] intValue];
这是导致麻烦的最后一行,我已经做到了这一点:
func peerDidChangeStateWithNotification(notification: NSNotification)
{
if let userInfo : AnyObject = notification.userInfo? {
let peerID = userInfo["peerID"] as MCPeerID
let state = userInfo["state"] as MCSessionState
但无法将“state”条目输入MCSessionState类型,得到错误:
'AnyObject' is not convertible to 'MCSessionState'
任何人都可以帮忙......?对Swift来说很新,很抱歉,如果这是一个明显的...
非常感谢,佛朗哥。
更新9sep:
首先设置userInfo对象的代码如下所示,据我所知调用toRaw()方法应该只是意味着它将它视为存储Int ...?在这种情况下,我不知道为什么你的原始答案不起作用......
func session(session: MCSession!, peer peerID: MCPeerID!, didChangeState state: MCSessionState)
{
var dict = ["peerID": peerID, "state": state.toRaw()]
NSNotificationCenter.defaultCenter().postNotificationName("MCDidChangeStateNotification", object: nil, userInfo: dict)
}
更新2 9sep:
知道了!如果其他人正在遵循相同的教程,则转换函数的完整工作版本如下所示。非常感谢你的帮助Edwin Vermeer:
func peerDidChangeStateWithNotification(notification: NSNotification)
{
if let userInfo : AnyObject = notification.userInfo?
{
let peerID = userInfo["peerID"] as MCPeerID
let peerDisplayName = peerID.displayName
let state: MCSessionState = MCSessionState.fromRaw(Int(userInfo["state"] as NSNumber)) as MCSessionState!
if (state != MCSessionState.Connecting)
{
if (state == MCSessionState.Connected)
{
arrayConnectedDevices.append(peerDisplayName)
}
else if (state == MCSessionState.NotConnected)
{
if (arrayConnectedDevices.count > 0)
{
if let i = find(arrayConnectedDevices, peerDisplayName)
{
arrayConnectedDevices.removeAtIndex(i)
}
}
}
}
}
}
答案 0 :(得分:1)
您可以使用它将int转换为枚举:
let state: MCSessionState = MCSessionState.fromRaw(Int(userInfo["state"] as NSNumber)) as MCSessionState!