애플의 icloud 서비스는 아이폰 뿐만아니라 아이패드, 맥북 등 다른 기기들과 호환성있게 사용 할 수 있는데 이러한 애플리케이션 간의 동기화를 아이클라우드의 key-value storage 가 제공한다.


해당 예제는 sotryboard 에 textfiled 와 버튼을 하나 만들고 텍스트 필드에 값을 입력하고 버튼으로 저장하면 해당 입력값이 키로 저장이 되고 다른 기기에서 동일한 애플리케이션을 실행해서 다른 키를 입력하여 저장하면 사용한 기기외 다른 기기에 알림창으로  키값이 변경되었다고 알려주는 간단한 예제이다.


프로젝트 메뉴중 capabilities 탭에서 icloud 사용을 활성화 하고 key-value storage 의 체크박스에 체크를 한다.




아래는 해당 예제의 viewController.swift 파일의 전체 소스이다.


import UIKit


class ViewController: UIViewController {

    

    var keyStore : NSUbiquitousKeyValueStore?

    

    @IBOutlet var textField: UITextField!

    

    @IBAction func saveKey(sender: AnyObject) {

        

        keyStore?.setString(textField.text, forKey: "MyString")

        keyStore?.synchronize()

    }


    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

        keyStore = NSUbiquitousKeyValueStore()

        let storedString = keyStore?.stringForKey("MyString")

        if let stringValue = storedString {

            textField.text = stringValue

        }

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "ubiquitousKeyValueStoreDidChange:", name: NSUbiquitousKeyValueStoreDidChangeExternallyNotification, object: keyStore)

        

    }

    

    func ubiquitousKeyValueStoreDidChange(notification : NSNotification) {

        let alert = UIAlertController(title: "Change detected", message: "iCloud key-value-store change detected", preferredStyle: UIAlertControllerStyle.Alert)

        let cancelAction = UIAlertAction(title: "OK", style: .Cancel, handler: nil)

        alert.addAction(cancelAction)

        self.presentViewController(alert, animated: true, completion: nil)

        textField.text = keyStore?.stringForKey("MyString")

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }



}






위의 
코드는  "핵심만 골라 배우는 ios 9 프로그래밍 (닐스미스 지음/ 황반석 옮김)" 에 있는 예제를 참고하여 작성하였습니다.

+ Recent posts