【问题标题】:Type 'UIViewController' does not conform to protocol 'WCSessionDelegate'类型“UIViewController”不符合协议“WCSessionDelegate”
【发布时间】:2016-10-20 03:11:09
【问题描述】:

自从在 Xcode 8(Beta 1)和 Swift 3 上升级后,我在这一行出现了错误:

class CloudViewController: UIViewController, WCSessionDelegate {

上面写着:

类型“UIViewController”不符合协议 'WCSessionDelegate'

这是我的(使用 Xcode 7 和 Swift 2)代码:

override func viewDidLoad() {
    super.viewDidLoad()

    if(WCSession.isSupported()){
        self.session = WCSession.default()
        self.session.delegate = self
        self.session.activate()
    }
}

func session(_ session: WCSession, didReceiveMessage message: [String : AnyObject]) {

    print("didReceiveMessage")

    watchMessageHandler.getMessage(message)

}

这个错误也出现在 WKInterfaceController 类中。

【问题讨论】:

  • 你建立/清理项目了吗?
  • @AkshanshThakur 是的,多次
  • 如果您阅读构建输出中的完整错误,它会告诉您您不符合协议的原因
  • 我认为您忘记实现协议构造所需的方法

标签: ios swift watchkit watchconnectivity watchos-3


【解决方案1】:

使用 Swift 3,您应该根据新协议实现这些方法

session:activationDidCompleteWithState:error:

sessionDidBecomeInactive:

sessionDidDeactivate:

因为它们不再在协议上标记为可选。

【讨论】:

    【解决方案2】:

    每个协议都带有一组方法,您应该实现这些方法以符合它们。您必须在您的类中编写这些方法以符合它。

    例如,在一个 UIViewController 中,如果你决定有一个 tableView,你必须添加UITableViewDataSourceUITableViewDelegate 协议,像这样:

    class ViewController : UIViewController, UITableViewDataSource, UITableViewDelegate  {
    
    }
    

    但是,这不是协议的完整实现。这只是声明。

    要真正让您的视图控制器符合协议,您必须实现两种方法,即:cellForRowAtIndexPathnumberOfRowsInSection。这是协议的要求。

    所以,完整的实现应该是这样的:

    class ViewController : UIViewController, UITableViewDataSource, UITableViewDelegate  {
    
         override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
             let cell = tableView.dequeueReusableCellWithIdentifier("cellID", forIndexPath: indexPath) as! ExperienceCell
    
             return cell
         }
    
         override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            // #warning Incomplete implementation, return the number of rows
            return 0
         }
    
    }
    

    因此,您必须查看文档并找到您的协议要求类实现哪些方法。 那应该可以解决这个问题。而且我认为这与 Xcode 8 或 swift 3 无关

    编辑这里:这是apple documentation says

    此协议的大多数方法都是可选的。您实现响应您的应用程序支持的数据传输操作所需的方法。但是,应用应实现对 session:activationDidCompleteWithState:error: 方法的支持以支持异步激活,并且 iPhone 应用中的委托应实现 sessionDidBecomeInactive: 和 sessionDidDeactivate: 方法以支持多个 Apple Watch。

    【讨论】:

      【解决方案3】:

      在您的 CloudViewController 中添加此方法

      internal func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: NSError?){
      }
      

      这个错误提示你需要实现WCSessionDelegate所需的协议方法

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-23
        • 2023-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多