0

自从升级到 Xcode 11.2 并构建和运行我的应用程序以来,Swift if let 块一直在报告失败,否则它总是可以正常工作。这是失败的代码。

public func remoteClient(receivedData data: [String : Any]?, fromPeer peerID: MCPeerID) {

  let params = data?["params"] as? [String:Any] 

  NSLog("Received image \(params!["timestamp"])")

  if let imgData = params?["image"] as? Data, let timeStamp = params?["timestamp"] as? CMTime
   {
           NSLog("Handling image response")
           handleImageResponse(imgData, timeStamp: timeStamp)

    } else {
           NSLog("Image response failed")
    }

}

这是控制台上打印的内容

  2019-11-02 23:47:52.342324+0530 MyApp [312:9779] Received image Optional(CMTime: {34515835925000/1000000000 = 34515.836})
  2019-11-02 23:47:52.343251+0530 MyApp[312:9779] Image response failed

在“if let”中删除对 CMTime 的检查可以解决问题,但是如何从 params 字典中提取 CMTime?

  1. 我想知道,使用 Xcode 11.2 构建时突然发生了什么变化?

  2. params!["timestamp"] 正在控制台中打印 CMTime,那么 if let 分配失败的原因是什么?

是 CMTime 失败了,我试过这个:

   if let imgData = params?["image"] as? Data, let timeStamp = params?["timestamp"] as? Any {

      let time = timeStamp as! CMTime

   }

我遇到了崩溃:

 Could not cast value of type 'CMTimeAsValue' (0x10ce321d8) to '__C.CMTime' (0x2355bab00).
4

1 回答 1

1

显然,时间作为NSValue包装 a 存储在字典中CMTime。在这种情况下,提取时间的正确方法是

if let val = params["timestamp"] as? NSValue {
    let time = val.timeValue
    // ...
}

另见NSValue(time:)NSValue.timeValue

于 2019-11-02T18:46:03.317 回答