2013 이전/iOS개발

[iOS 개발] iCloud keyValue Data Storage 사용

하구루 2017. 2. 25. 16:20

유니버셜 앱을 개발하여 배포할때 각 앱의 설정을 연동할때 유용하게 사용할 수 있는

 
iCloud keyValue Data Storage를 소개 해보려고 한다.

앱 내에서 iCloud 연동을 위한 설정은 아래 포스팅을 통해 진행하면 된다.


설정이 다되면 이를 이용하는 것은 매우 간단하다.

NSUserDefault를 이용해 본 사용자라면 보자 마자 이해 할 수 있을것이다.

NSUbiquitousKeyValueStore 라는 클래스를 통해서 쉽게 사용 할수 있다.


 NSUbiquitousKeyValueStore* store = [NSUbiquitousKeyValueStore defaultStore];
        
[store setBool:YES forKey:@"kUsrDefAskDeleting"];

 [store synchronize];
보는 것처럼 간단하게 defaultStore 메소드를 통해서 keyValue를 셋할수 있는 객체를 얻어 올수 있고,
 
해당 객체에 set 메소드를 통해서 BOOL 변수 뿐 아니라
- (void)setString:(NSString *)aString forKey:(NSString *)aKey;
- (void)setData:(NSData *)aData forKey:(NSString *)aKey;
- (void)setArray:(NSArray *)anArray forKey:(NSString *)aKey;
- (void)setDictionary:(NSDictionary *)aDictionary forKey:(NSString *)aKey;
- (void)setLongLong:(long long)value forKey:(NSString *)aKey;
- (void)setDouble:(double)value forKey:(NSString *)aKey;
- (void)setBool:(BOOL)value forKey:(NSString *)aKey;
위 메소드를 통해서 여러 형태의 객체를 저장할 수 있다.
 
그리고 모든 저장 절차가 끝나면

synchronize 메소드를 호출해 주면 된다.

synchronize를 호출했다고 해서, 해당 하는 내용이 iCloud로 바로 전송이 되어지는 것은 아니다.

해당 메소드를 호출하면 해당하는 내용이 즉시 파일에 저장이 된다.

이후 iCloud로 전송이 되는것은 시스템이 알아서 해준다.

즉, iCloud로 싱크 시키는것을 명시적으로 해줄 수 있는 방법은 없다.

그렇다고, 그 iCloud로 싱크되는 시점이 늦지는 않으니 걱정하지 않아도 될것이다.

네트워크가 안정적인 환경에서 테스트 해보았을때 30초 안에는 적용이 되어 다른 디바이스에 전달되는것을 확인 하였다.

이제 변경된 사항을 iCloud로 부터 받아 보는 방법을 보겠다.

이도 매우 간단하다.
 NSUbiquitousKeyValueStore *keyStore = [NSUbiquitousKeyValueStore defaultStore];
        
[[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector: @selector(ubiquitousKeyValueStoreDidChange:)
                                                     name: NSUbiquitousKeyValueStoreDidChangeExternallyNotification
                                                   object:keyStore];
    
[keyStore synchronize];

위 와 같은 방법으로 notification을 등록해 준후에 해당 메소드를 구현해주기만 하면 된다.

-(void) ubiquitousKeyValueStoreDidChange: (NSNotification *)notification
{
    // Get the list of keys that changed.
    NSDictionary* userInfo = [notification userInfo];
    NSNumber* reasonForChange = [userInfo objectForKey:NSUbiquitousKeyValueStoreChangeReasonKey];
    NSInteger reason = -1;
    
    // If a reason could not be determined, do not update anything.
    if (!reasonForChange)
        return;
    
    // Update only for changes from the server.
    reason = [reasonForChange integerValue];
    if ((reason == NSUbiquitousKeyValueStoreServerChange) ||
        (reason == NSUbiquitousKeyValueStoreInitialSyncChange)) {
        // If something is changing externally, get the changes
        // and update the corresponding keys locally.
        NSArray* changedKeys = [userInfo objectForKey:NSUbiquitousKeyValueStoreChangedKeysKey];
        NSUbiquitousKeyValueStore* store = [NSUbiquitousKeyValueStore defaultStore];
        NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
        
        // This loop assumes you are using the same key names in both
        // the user defaults database and the iCloud key-value store
        for (NSString* key in changedKeys) {
            id value = [store objectForKey:key];
            [userDefaults setObject:value forKey:key];
        }
    }
}

위 처럼 구현을 하였는데, 이는 apple developer page에서 그대로 가져다 쓴것이다.


NSUserDefault를 통해서 셋팅을 관리 한다면 그대로 가져다 써도 무방할 것이다.

 해당 내용은 그렇게 어렵지 않으므로 추가 적인 설명은 생략 하겠다. 


 사용이 간단하니 한번씩 앱에 적용해 보는 것도 나쁘지 않을 것으로 보인다.


반응형