저는 앱개발할때 React-Native를 주로 사용합니다
이번에 워치앱을 개발하고 싶어서 자료를 찾던중 자료찾기가 어려워서 했던 성공했던 내용 공유 드립니다
우선 환경은 React Native + SwiftUi 입니다
우선 React-Native 폴더에서 react-native-watch-connectivity 을 설치해줍니다.
npm install react-native-watch-connectivity --save
# or
yarn add react-native-watch-connectivity
후에
cd ios
pod install
import React, {useEffect, useState} from 'react';
import {
Alert,
SafeAreaView,
Text,
TextInput,
TouchableOpacity,
} from 'react-native';
import {sendMessage, watchEvents} from 'react-native-watch-connectivity';
const App = () => {
const [messageFromWatch, setMessageFromWatch] = useState('Waiting...');
const [message, setMessage] = useState('');
const messageListener = () =>
//여기로 메시지 들어옴
watchEvents.on('message', (message: any) => {
setMessageFromWatch(message.watchMessage);
});
useEffect(() => {
messageListener();
}, []);
return (
<SafeAreaView>
<Text>Received from Watch App!</Text>
<Text>{messageFromWatch}</Text>
<Text>Send to Watch App!</Text>
<TextInput placeholder="Message" onChangeText={setMessage}>
{message}
</TextInput>
<TouchableOpacity
onPress={() =>
sendMessage(
{messageFromApp: message},
reply => {
console.log(reply);
},
error => {
if (error) {
Alert.alert(
"메시지 전송 실패 🤔",
);
}
},
)
}>
<Text>SEND!</Text>
</TouchableOpacity>
</SafeAreaView>
);
};
export default App;
messageListener를 통해 워치로부터 메시지를 수신받고 sendMessage를 통해 워치로 메시지를 전달합니다. 간단하죠?
그리고 이제 스위프트 코드를 작성해야하는데 여기서 삽질 오지게함
잘따라오십시요
옛 버전에서는 watch app for ios 등등 여러개였었는데 통합된듯
이게 2번에서 말한 통합된 내용인듯합니다.
저는 WatchApp이라는 이름으로 진행하겠습니다
WachApp Watch App이 새로 생김, 이름뒤에 자동으로 뭐가 붙는데 거슬리기는 하나 튜토리얼이기에 넘어갑시다
폴더보면 PhoneConnector이라는 파일이있는데, 저는 미리 만들어놨기때문에 존재하는거지 원래 없습니다.
watchApp 폴더에서 new
watchOS > swift 파일 선택
PhoneConnector 생성
import SwiftUI
import WatchKit
import WatchConnectivity
final class PhoneConnector: NSObject ,ObservableObject{
@Published var receivedMessage = "Waiting..."
var session: WCSession
init(session: WCSession = .default) {
self.session = session
super.init()
if WCSession.isSupported() {
session.delegate = self
session.activate()
}
}
}
extension PhoneConnector: WCSessionDelegate {
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
}
func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
guard let messageFromApp = message["messageFromApp"] as? String else { return }
DispatchQueue.main.async {
self.receivedMessage = messageFromApp
}
}
}
라이브러리가 제공하는 기본 형태입니다. 대강 읽어보시면 세션만들어서 메시지받고 receivedMessage라는 메시지를 퍼블릭하게 공유한다 정도로 이해하면 됩니다.
import SwiftUI
struct ContentView: View {
@ObservedObject var phoneConnector = PhoneConnector()
var body: some View {
VStack(alignment: .leading, spacing: 20) {
VStack(alignment: .leading, spacing: 5) {
Text("Send to Watch")
Button {
self.sendMessage()
} label: {
Text("Send")
}
}
VStack(alignment: .leading, spacing: 5) {
Text("Message from App")
Text(self.phoneConnector.receivedMessage)
}
}
}
private func sendMessage() {
let randomNumber = String(Int.random(in: 0..<1000))
let message: [String: Any] = ["watchMessage": randomNumber]
self.phoneConnector.session.sendMessage(message, replyHandler: nil) { (error) in
print(error.localizedDescription)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
phoneConnector를 연결해서 수신하고 랜덤 문자열을 송신하는 UI를 구성했습니다
watchApp을 타겟으로 실행해야합니다.
실행하면 메트로가 켜지고 ios랑 워치 시뮬레이터가 켜집니다.
여기까지 오면 끝났습니다
반대로도 테스트를 해보죠
송수신 모두 잘되는거 확인했습니다.
해당 코드는 깃허브에서 확인 할 수 있습니다.
다음에는 백그라운드도 올려볼게유
https://melonplaymods.com/2023/06/11/military-transport-vehicle-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/btr-90-mod-for-melon-playground-2/
https://melonplaymods.com/2023/06/11/shadow-fight-2-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/decorative-rocket-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/gundam-rx-77-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/snow-lotus-ice-cubes-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/seeks-hallway-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/items-from-terraria-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/crocodile-from-one-piece-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/david-beaver-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/classic-house-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/military-boat-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/minecraft-item-pack-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/plants-vs-zombies-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/theme-of-the-game-pack-man-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/tank-mod-for-melon-playground-3/
https://melonplaymods.com/2023/06/10/puss-in-boots-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/thor-hammer-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/glitch-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/pack-for-vegetables-and-fruits-mod-for-melon-playground/