WatchOS

[WatchOS] 애플워치에서 데이터 저장하기

Frankie 2021. 11. 11. 15:01

이번 글에서는 Xcode에서 애플워치에서 데이터 저장하는 법을 알아보려합니다.

 

1. 우선 WatchOS 프로젝트를 생성합니다.

ios 앱과 연동하려면 첫 번째를 클릭하고 애플워치 앱만으로 만드려면 두 번째를 클릭해서 생성합니다.

 

2.



우선 위의 그림과 같이 + 버튼을 눌러서 인터페이스로 Button과 Label을 배치합니다.



그러면 이런 화면이 구성이 됩니다.

이제 코드를 보겠습니다. WatchKit Extension 폴더에서 InterfaceController.swfit 파일로 들어갑니다.

그러면 이제 거기에서

// InterfaceController.swift

import WatchKit
import Foundation


class InterfaceController: WKInterfaceController {
    
    @IBOutlet var itemLabel: WKInterfaceLabel!
    
    let userDefualts = UserDefaults()

    override func awake(withContext context: Any?) {
        // Configure interface objects here.
        self.itemLabel.setText(userDefualts.value(forKey: "item") as? String)
    }
    
    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
    }

    @IBAction func addButtonTapped() {
        self.presentTextInputController(withSuggestions: nil, allowedInputMode: .allowEmoji, completion: { result in
            guard let result = result else { return }
            OperationQueue.main.addOperation {
                self.dismissTextInputController()
                self.itemLabel.setText(result[0] as? String)
                self.userDefualts.setValue(result[0], forKey: "item")
            }
        })
    }
}

이와 같은 코드를 작성하면 됩니다. 그리고 @IBOutlet과 @IBAction은 WatchKit App 폴더에서 Interface 파일로 들어간 뒤

'WatchOS' 카테고리의 다른 글

[WatchOS] React-Native 앱에서 데이터 받는 함수  (0) 2021.11.19
[IOS] Delegate  (0) 2021.11.19
[WatchOS] React-Native와 WatchOS 연결하기  (0) 2021.11.19