gpt4 book ai didi

xcode - 尝试在 Swift 的多点连接测试应用程序中使用 NSNotification

转载 作者:可可西里 更新时间:2023-11-01 02:28:03 26 4
gpt4 key购买 nike

一直在学习本教程:

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 很陌生,很抱歉,如果这是一个明显的问题......

非常感谢,佛朗哥。


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)

}

9 月 2 日更新:

知道了!如果其他人正在遵循同一教程,则转换函数的完整工作版本如下所示。非常感谢埃德温·维米尔 (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)
}
}
}
}
}
}

最佳答案

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

let state: MCSessionState = MCSessionState.fromRaw(Int(userInfo["state"] as NSNumber)) as MCSessionState!

关于xcode - 尝试在 Swift 的多点连接测试应用程序中使用 NSNotification,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25733111/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com