I have a variable in Dictionary type. How can I change the data on the Section Function to Dictionary?
Stringdata in the Section function shows the same value in both variables? I have to separate these values. How can I do that ?
ViewModel
Random Word Session Func
Answer Session
Session Func
Stringdata in the Section function shows the same value in both variables? I have to separate these values. How can I do that ?
ViewModel
Code Block @Published var dictionaryValues:[String: String] = ["word":"","answer":""]
Random Word Session Func
Code Block func randomWordSession() { guard let word = dictionaryValues["word"]?.data(using: .utf8) else { return } guard let pears = session?.connectedPeers else { return } do { try session?.send(word, toPeers: pears, with: .reliable) } catch { print(error.localizedDescription) } }
Answer Session
Code Block func answerSession() { guard let answer = dictionaryValues["answer"]?.data(using: .utf8) else { return } guard let peers = session?.connectedPeers else { return } do { try session?.send(answer, toPeers: peers, with: .reliable) } catch { print(error.localizedDescription) } }
Session Func
Code Block func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) { if let stringData = String(data: data, encoding: .utf8) { DispatchQueue.main.async { self.dictionaryValues["word"] = stringData self.dictionaryValues["answer"] = stringData } } }
Yes, as I said, you have to encode/decode this. Try this:
Code Block extension Encodable { func encode(with encoder: JSONEncoder = JSONEncoder()) throws -> Data { return try encoder.encode(self) } } extension Decodable { static func decode(with decoder: JSONDecoder = JSONDecoder(), from data: Data) throws -> Self { return try decoder.decode(Self.self, from: data) } } func randomWordSession() { guard let word = try? MyMessage(type: 0, data: dictionaryValues["word"] ?? "").encode() else { return } ... } func answerSession() { guard let answer = try? MyMessage(type: 1, data: dictionaryValues["answer"] ?? "").encode() else { return } ... }