How can I send userDefaults data to Watch?

I’m doing an basic App for create notes and subnotes in iPhone and show them in Watch. I did the both CRUD but I can’t view the data in Watch. I’m using userDefaults because It’s so simple app.

I tried add NSObject and WCSessionDelegate to my NoteViewModel but doesn’t work. When I start the app, I get ‘WCSessionActivationState(rawValue: 2)’.

Here is my NoteViewModel.swift:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import Combine
import Foundation
import WatchConnectivity
class NoteViewModel: NSObject, WCSessionDelegate, ObservableObject {
@Published var notes: [Note] = []
func addNote(title: String) {
let newNote = Note(title: title, subNotes: [])
notes.append(newNote)
saveNotes()
}
func addSubNote(to note: Note, title: String, content: String) {
if let index = notes.firstIndex(where: { $0.id == note.id }) {
let newSubNote = SubNote(title: title, content: content)
notes[index].subNotes.append(newSubNote)
saveNotes()
}
}
func removeNote(note: Note) {
notes.removeAll { $0.id == note.id }
saveNotes()
}
func removeSubNote(from note: Note, subNote: SubNote) {
if let index = notes.firstIndex(where: { $0.id == note.id }) {
notes[index].subNotes.removeAll { $0.id == subNote.id }
saveNotes()
}
}
func updateNote(note: Note, newTitle: String) {
if let index = notes.firstIndex(where: { $0.id == note.id }) {
notes[index].title = newTitle
saveNotes()
}
}
override init() {
super.init()
if WCSession.isSupported() {
WCSession.default.delegate = self
WCSession.default.activate()
self.notes = loadNotes()
}
}
func session(
_ session: WCSession,
activationDidCompleteWith activationState: WCSessionActivationState,
error: Error?
) {
if let error = error {
print("Error al activar la sesión: (error.localizedDescription)")
} else {
print("Sesión activada con estado: (activationState)")
}
}
#if os(iOS)
func sessionDidBecomeInactive(_ session: WCSession) { }
func sessionDidDeactivate(_ session: WCSession) {
session.activate()
}
func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
if let notesArray = message["notes"] as? [[String: Any]] {
let decoder = JSONDecoder()
if let data = try? JSONSerialization.data(withJSONObject: notesArray, options: []),
let notes = try? decoder.decode([Note].self, from: data) {
self.notes = notes
saveNotes()
}
}
}
#endif
private func saveNotes() {
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(notes) {
if let defaults = UserDefaults(suiteName: "group.lucasleone.WatchNotesApp") {
defaults.set(encoded, forKey: "notes")
}
sendNotesToWatch(notes: notes)
}
}
private func loadNotes() -> [Note] {
if let defaults = UserDefaults(suiteName: "group.lucasleone.WatchNotesApp"),
let savedNotes = defaults.data(forKey: "notes") {
let decoder = JSONDecoder()
if let loadedNotes = try? decoder.decode([Note].self, from: savedNotes) {
return loadedNotes
}
}
return []
}
private func sendNotesToWatch(notes: [Note]) {
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(notes) {
let notesDict = try? JSONSerialization.jsonObject(with: encoded, options: []) as? [[String: Any]]
if WCSession.default.isReachable {
WCSession.default.sendMessage(["notes": notesDict ?? []], replyHandler: nil, errorHandler: { error in
print("Error enviando mensaje: (error.localizedDescription)")
})
}
}
}
}
</code>
<code>import Combine import Foundation import WatchConnectivity class NoteViewModel: NSObject, WCSessionDelegate, ObservableObject { @Published var notes: [Note] = [] func addNote(title: String) { let newNote = Note(title: title, subNotes: []) notes.append(newNote) saveNotes() } func addSubNote(to note: Note, title: String, content: String) { if let index = notes.firstIndex(where: { $0.id == note.id }) { let newSubNote = SubNote(title: title, content: content) notes[index].subNotes.append(newSubNote) saveNotes() } } func removeNote(note: Note) { notes.removeAll { $0.id == note.id } saveNotes() } func removeSubNote(from note: Note, subNote: SubNote) { if let index = notes.firstIndex(where: { $0.id == note.id }) { notes[index].subNotes.removeAll { $0.id == subNote.id } saveNotes() } } func updateNote(note: Note, newTitle: String) { if let index = notes.firstIndex(where: { $0.id == note.id }) { notes[index].title = newTitle saveNotes() } } override init() { super.init() if WCSession.isSupported() { WCSession.default.delegate = self WCSession.default.activate() self.notes = loadNotes() } } func session( _ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error? ) { if let error = error { print("Error al activar la sesión: (error.localizedDescription)") } else { print("Sesión activada con estado: (activationState)") } } #if os(iOS) func sessionDidBecomeInactive(_ session: WCSession) { } func sessionDidDeactivate(_ session: WCSession) { session.activate() } func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) { if let notesArray = message["notes"] as? [[String: Any]] { let decoder = JSONDecoder() if let data = try? JSONSerialization.data(withJSONObject: notesArray, options: []), let notes = try? decoder.decode([Note].self, from: data) { self.notes = notes saveNotes() } } } #endif private func saveNotes() { let encoder = JSONEncoder() if let encoded = try? encoder.encode(notes) { if let defaults = UserDefaults(suiteName: "group.lucasleone.WatchNotesApp") { defaults.set(encoded, forKey: "notes") } sendNotesToWatch(notes: notes) } } private func loadNotes() -> [Note] { if let defaults = UserDefaults(suiteName: "group.lucasleone.WatchNotesApp"), let savedNotes = defaults.data(forKey: "notes") { let decoder = JSONDecoder() if let loadedNotes = try? decoder.decode([Note].self, from: savedNotes) { return loadedNotes } } return [] } private func sendNotesToWatch(notes: [Note]) { let encoder = JSONEncoder() if let encoded = try? encoder.encode(notes) { let notesDict = try? JSONSerialization.jsonObject(with: encoded, options: []) as? [[String: Any]] if WCSession.default.isReachable { WCSession.default.sendMessage(["notes": notesDict ?? []], replyHandler: nil, errorHandler: { error in print("Error enviando mensaje: (error.localizedDescription)") }) } } } } </code>
import Combine
import Foundation
import WatchConnectivity

class NoteViewModel: NSObject, WCSessionDelegate, ObservableObject {
    @Published var notes: [Note] = []
    
    func addNote(title: String) {
        let newNote = Note(title: title, subNotes: [])
        notes.append(newNote)
        saveNotes()
    }

    func addSubNote(to note: Note, title: String, content: String) {
        if let index = notes.firstIndex(where: { $0.id == note.id }) {
            let newSubNote = SubNote(title: title, content: content)
            notes[index].subNotes.append(newSubNote)
            saveNotes()
        }
    }

    func removeNote(note: Note) {
        notes.removeAll { $0.id == note.id }
        saveNotes()
    }

    func removeSubNote(from note: Note, subNote: SubNote) {
        if let index = notes.firstIndex(where: { $0.id == note.id }) {
            notes[index].subNotes.removeAll { $0.id == subNote.id }
            saveNotes()
        }
    }

    func updateNote(note: Note, newTitle: String) {
        if let index = notes.firstIndex(where: { $0.id == note.id }) {
            notes[index].title = newTitle
            saveNotes()
        }
    }

    override init() {
        super.init()
        if WCSession.isSupported() {
            WCSession.default.delegate = self
            WCSession.default.activate()
            self.notes = loadNotes()
        }
    }

    func session(
        _ session: WCSession,
        activationDidCompleteWith activationState: WCSessionActivationState,
        error: Error?
    ) {
        if let error = error {
            print("Error al activar la sesión: (error.localizedDescription)")
        } else {
            print("Sesión activada con estado: (activationState)")
        }
    }

    #if os(iOS)
    func sessionDidBecomeInactive(_ session: WCSession) { }

    func sessionDidDeactivate(_ session: WCSession) {
        session.activate()
    }

    func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
        if let notesArray = message["notes"] as? [[String: Any]] {
            let decoder = JSONDecoder()
            if let data = try? JSONSerialization.data(withJSONObject: notesArray, options: []),
               let notes = try? decoder.decode([Note].self, from: data) {
                self.notes = notes
                saveNotes()
            }
        }
    }
    #endif

    private func saveNotes() {
        let encoder = JSONEncoder()
        if let encoded = try? encoder.encode(notes) {
            if let defaults = UserDefaults(suiteName: "group.lucasleone.WatchNotesApp") {
                defaults.set(encoded, forKey: "notes")
            }
            sendNotesToWatch(notes: notes)
        }
    }

    private func loadNotes() -> [Note] {
        if let defaults = UserDefaults(suiteName: "group.lucasleone.WatchNotesApp"),
           let savedNotes = defaults.data(forKey: "notes") {
            let decoder = JSONDecoder()
            if let loadedNotes = try? decoder.decode([Note].self, from: savedNotes) {
                return loadedNotes
            }
        }
        return []
    }

    private func sendNotesToWatch(notes: [Note]) {
        let encoder = JSONEncoder()
        if let encoded = try? encoder.encode(notes) {
            let notesDict = try? JSONSerialization.jsonObject(with: encoded, options: []) as? [[String: Any]]
            if WCSession.default.isReachable {
                WCSession.default.sendMessage(["notes": notesDict ?? []], replyHandler: nil, errorHandler: { error in
                    print("Error enviando mensaje: (error.localizedDescription)")
                })
            }
        }
    }
}

And in the watch, I tried this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>struct HomeView: View {
@StateObject var viewModel = NoteViewModel()
var body: some View {
NavigationView {
List {
ForEach(viewModel.notes) { note in
NavigationLink(
destination: NoteDetailView(
note: note, viewModel: viewModel)
) {
Text(note.title)
}
}
}
.navigationTitle("Notas")
}
}
}
</code>
<code>struct HomeView: View { @StateObject var viewModel = NoteViewModel() var body: some View { NavigationView { List { ForEach(viewModel.notes) { note in NavigationLink( destination: NoteDetailView( note: note, viewModel: viewModel) ) { Text(note.title) } } } .navigationTitle("Notas") } } } </code>
struct HomeView: View {
    @StateObject var viewModel = NoteViewModel()

    var body: some View {
        NavigationView {
            List {
                ForEach(viewModel.notes) { note in
                    NavigationLink(
                        destination: NoteDetailView(
                            note: note, viewModel: viewModel)
                    ) {
                        Text(note.title)
                    }
                }
            }
            .navigationTitle("Notas")
        }
    }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật