0

I have created an app for iOS that shows items from coredata in a list. I want to add an item to that list whenever a button in the watchOS app is pressed. I found the framework WatchConnectivity. I have gotten it to a point where an alert pops up on the iPhone but I dont know how to transform the database entry from the watch so that I can send it to the iPhones database.

Whole code can be found in the github branch: https://github.com/glottis0q/Work-Time-Manager/tree/issue-119

//
//  WatchConnectivityManager.swift
//  WeatherApp
//
//  Created by Bahalek on 2022-01-04.
//

import Foundation
import WatchConnectivity

struct NotificationMessage: Identifiable {
    let id = UUID()
    let text: String
}

final class WatchConnectivityManager: NSObject, ObservableObject {
    static let shared = WatchConnectivityManager()
    @Published var notificationMessage: NotificationMessage? = nil
    
    private override init() {
        super.init()
        
        if WCSession.isSupported() {
            WCSession.default.delegate = self
            WCSession.default.activate()
        }
    }
    
    private let kMessageKey = "message"
    
    func sendMessage(_ message: String) {
        guard WCSession.default.activationState == .activated else {
          return
        }
        #if os(iOS)
        guard WCSession.default.isWatchAppInstalled else {
            return
        }
        #else
        guard WCSession.default.isCompanionAppInstalled else {
            return
        }
        #endif
        
        WCSession.default.sendMessage([kMessageKey : message], replyHandler: nil) { error in
            print("Cannot send message: \(String(describing: error))")
        }
    }
    
    func sendMessageData(_ messageData: Data) {
        guard WCSession.default.activationState == .activated else {
          return
        }
        #if os(iOS)
        guard WCSession.default.isWatchAppInstalled else {
            return
        }
        #else
        guard WCSession.default.isCompanionAppInstalled else {
            return
        }
        #endif
        
        WCSession.default.sendMessageData(messageData, replyHandler: nil) { error in
            print("Cannot send message: \(String(describing: error))")
        }
    }
}

extension WatchConnectivityManager: WCSessionDelegate {
    func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
        if let notificationText = message[kMessageKey] as? String {
            DispatchQueue.main.async { [weak self] in
                self?.notificationMessage = NotificationMessage(text: notificationText)
            }
        }
    }
    
    func session(_ session: WCSession,
                 activationDidCompleteWith activationState: WCSessionActivationState,
                 error: Error?) {}
    
    #if os(iOS)
    func sessionDidBecomeInactive(_ session: WCSession) {}
    func sessionDidDeactivate(_ session: WCSession) {
        session.activate()
    }
    #endif
}
//
//  ToolbarTimesView.swift
//  Work Time Manager
//
//  Created by John Doe on 10.02.22.
//

import SwiftUI
import CoreLocation

struct WatchToolbarView: View {
    (...)

    var body: some View {
        (...)
    }
    
    private func addWork() {
        (...)
                    let pause = Time(context: viewContext)
                    pause.start = Calendar.current.date(byAdding: .second, value: Int(0.1), to: times.first!.end!)!
                    pause.end = Calendar.current.date(byAdding: .second, value: -Int(0.1), to: Date())!
                    pause.type = "pause"
                    pause.startLocationLat = times.first!.endLocationLat
                    pause.startLocationLong = times.first!.endLocationLong
                    
                    WatchConnectivityManager.shared.sendMessageData(pause)
                }
            }
            
            (...)
        }
            (...)
    }
    (...)
}

struct WatchToolbarView_Previews: PreviewProvider {
    static var previews: some View {
        WatchToolbarView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
    }
}

Image of the code showing the error
Image of the code showing the error

Pablo
  • 13
  • 2
  • This might help https://stackoverflow.com/questions/68071301/saving-userinfo-received-via-watchconnectivity-to-coredata/68085918#68085918 – lorem ipsum Feb 28 '22 at 19:05
  • Thanks, that might help. So sendUserInfo would be correct to use instead of sendMessageData? Seems weird. – Pablo Mar 04 '22 at 06:11
  • I don't think there is a a right or wrong with that question. Either would work, the documentation could help you decide. Do some research on the differences. – lorem ipsum Mar 04 '22 at 12:25

0 Answers0