2

一直在关注本教程:

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

但无法将“状态”条目转换为 MCSessionState 类型,出现错误:

'AnyObject' is not convertible to 'MCSessionState'

任何人都可以帮助...?对 Swift 来说很新,如果这是一个明显的问题,很抱歉......

非常感谢,佛朗哥。


9 月 9 日更新:

首先设置 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)
                    }
                }
            }
        }
    }
}
4

1 回答 1

1

您可以使用它来将 int 转换为枚举:

let state: MCSessionState = MCSessionState.fromRaw(Int(userInfo["state"] as NSNumber)) as MCSessionState!
于 2014-09-08T21:28:12.150 回答