Ошибка при попытке декодировать данные объекта в приложении Apple Watch

Я пытаюсь отправить данные пользовательских объектов из части iOS моего приложения в часть Apple Watch. Мои данные, похоже, отправляются с телефона на часы, но не декодируются.

Я проверил, что приложение "Делегат" на телефоне настроено и отвечает правильно. Кроме того, мой пользовательский объект соответствует NSCoding, как и должно быть.

Вот делегат приложения на стороне iOS:

class AppDelegate: UIResponder, UIApplicationDelegate {



// MARK: - Class Properties
var window: UIWindow?
var session: WCSession? {
    didSet {
        if let session = session {
            // Set session delegate and activate
            session.delegate = self
            session.activate()
        }
    }
}



// MARK: - System Generated Functions
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // If watch connectivity session is supported, use default session
    if WCSession.isSupported() {
        session = WCSession.default
    }

    return true
}
}



extension AppDelegate: WCSessionDelegate {



// MARK: - System Generated Functions
func sessionDidDeactivate(_ session: WCSession) {}

func sessionDidBecomeInactive(_ session: WCSession) {}

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

func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
    DispatchQueue.main.async {
        // If message is received from watch, continue
        if(message["updateData"] as? Bool) != nil {
            // Reference class to be shared across devices
            NSKeyedArchiver.setClassName("Joy", for: Joy.self)

            // Reference main view controller and get current Joy data
            let viewController = ViewController()
            let joy = viewController.joy

            // Attempt to encode Joy data and send to watch
            guard let data = try? NSKeyedArchiver.archivedData(withRootObject: joy as Any, requiringSecureCoding: false)
                else {
                    fatalError("Error")
            }

            replyHandler(["updatedData": data])
        }
    }
  }
}

Вот функции кодирования и декодирования в моем пользовательском объекте:

required convenience init?(coder aDecoder: NSCoder) {
    // Set dummy data
    self.init(giveGoal: 1000, giveProgress: 2000, getProgress: 3000, payItForwardGoal: 4000, payItForwardProgress: 5000)

    // Decode Joy properties
    giveGoal = aDecoder.decodeObject(forKey: "giveGoalInt") as! Int
    giveProgress = aDecoder.decodeObject(forKey: "giveProgressInt") as! Int
    getProgress = aDecoder.decodeObject(forKey: "getProgressInt") as! Int
    payItForwardGoal = aDecoder.decodeObject(forKey: "payItForwardGoalInt") as! Int
    payItForwardProgress = aDecoder.decodeObject(forKey: "payItForwardProgressInt") as! Int
}



func encode(with aCoder: NSCoder) {
    // Encode Joy properties
    aCoder.encode(giveGoal, forKey: "giveGoalInt")
    aCoder.encode(giveProgress, forKey: "giveProgressInt")
    aCoder.encode(getProgress, forKey: "getProgressInt")
    aCoder.encode(payItForwardGoal, forKey: "payItForwardGoalInt")
    aCoder.encode(payItForwardProgress, forKey: "payItForwardProgressInt")
}

И вот блок кода, где я получаю ошибку:

func getData() {
    // Build message to send to iOS portion
    let joyValues: [String: Any] = ["updateData": true]

    // If a session is available, continue
    if let session = session, session.isReachable {

        // Send the message and handle reply from iOS portion
        session.sendMessage(joyValues, replyHandler: {
            replyData in

            print(replyData)

            DispatchQueue.main.async {
                // If data is received from iOS portion, begin to decode
                if let data = replyData["updatedData"] as? Data {
                    NSKeyedUnarchiver.setClass(Joy.self, forClassName: "Joy")

                    do {
                        // Attempt to decode Joy data
                        // THIS IS WHERE MY FAILURE OCCURS
                        guard let joyData = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? Joy else {
                                fatalError("Can't get Joy data")
                        }

                        // Reference decoded Joy data
                        self.joy = joyData

                        self.updateDisplay()
                    }

                    catch {
                        fatalError("Can't unarchive data: \(error)")
                    }
                }
            }
        }) { (error) in
            print(error.localizedDescription)
        }
    }
}

0 ответов

Другие вопросы по тегам