WatchOS

[WatchOS] React-Native와 WatchOS 연결하기

Frankie 2021. 11. 19. 11:53

우선 React-Native 폴더에서 react-native-watch-connectivity 을 설치해줍니다.

 

npm install react-native-watch-connectivity --save
# or
yarn add react-native-watch-connectivity

그 후 React-Native 폴더와 WatchKit 폴더를 Link 해주어야 합니다.

 

1) React-Native 버전이 0.60보다 낮은 경우

react-native link

2) 그 외 경우 (직접 연결)

// ios/Podfile

pod 'ReactNative 프로젝트이름', :path => '../node_modules/react-native-watch-connectivity'

이후 pod install을 진행해줍니다.

 

이제는 React-Native 폴더와 WatchOS 폴더에서 코드를 작성해주면 됩니다.

 

// Reaect-Native 폴더 코드

import React from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import * as Watch from 'react-native-watch-connectivity';
  
  const App = () => {
  
  sendMessageToWatch = () => {
    try {
      Watch.sendMessage({text: 'hi'}, (err, resp) => {
        if (!err) {
          console.log('response received', resp);
        } else {
          console.warn('error sending message to watch', err);
        }
      });
    } catch (error) {
      console.log(error);
    }
  };

  const testBtn = async (text) => {
    sendMessageToWatch();
  };

  return (
    <View>
      <Text>Test</Text>
      <TouchableOpacity onPress={getTestBtn}>
        <Button title={'테스트버튼'} onPress={testBtn} />
      </TouchableOpacity>
    </View>
  );
};

// WatchOS 폴더 코드(Xcode)

// InterfaceController.swift

import WatchKit
import Foundation
import WatchConnectivity

class InterfaceController: WKInterfaceController,WCSessionDelegate {
  var session: WCSession?
 
  @IBOutlet weak var testLabel: WKInterfaceLabel!
  
  override func awake(withContext context: Any?) {
    // Configure interface objects here.
    if WCSession.isSupported(){
      self.session = WCSession.default
      self.session?.delegate = self
      self.session?.activate()
    }
  }
  
  override func willActivate() {
    // This method is called when watch view controller is about to be visible to user
  }
  
  override func didDeactivate() {
    // This method is called when watch view controller is no longer visible
  }
  
  func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
    let text = message["text"] as! String
    self.testLabel.setText(text)
  }
}

 

이렇게 작성하고 나서 Simulator를 실행해서 ios, watch 시뮬레이터를 둘 다 실행한 후 테스트 해보면 잘 진행됩니다.

 

ReactNative, WatchOS 프로젝트 생성하는 등 초기 부분은 생략된 게 많으니 궁금한 게 있으면 물어보시면 될 것 같습니다!

 

참고 - https://github.com/mtford90/react-native-watch-connectivity

'WatchOS' 카테고리의 다른 글

[WatchOS] React-Native 앱에서 데이터 받는 함수  (0) 2021.11.19
[IOS] Delegate  (0) 2021.11.19
[WatchOS] 애플워치에서 데이터 저장하기  (0) 2021.11.11