반응형
LinkedIn 개발자로 성장하면서 남긴 발자취들을 확인하실 수 있습니다.
Github WWDC Student Challenge 및 Cherish, Tiramisul 등 개발한 앱들의 코드를 확인하실 수 있습니다.
개인 앱 : Cherish 내 마음을 들여다보는 시간, 체리시는 디자이너와 PM과 함께 진행 중인 1인 개발 프로젝트입니다.
10년 후, 20년 후 나는 어떤 스토리 텔러가 되어 있을지 궁금하다. 내가 만약에 아직 조금 더 탐구하고 싶은 게 있고, 궁금한 게 있다면, 그게 설사 지금 당장의 내 인생에 도움이 안 되는 것 같더라도 경험해보자. 그 경험들을 온전히 즐기며 내 것으로 만들고, 내 일에 녹여내고... 그러다보면 그 점들이 모여 나란 사람을 그려내는 선이 될 테니까.

Recent Posts
Recent Comments
Total
관리 메뉴

꿈꾸는리버리

[iCloudKit 시리즈 3] 나도 백엔드 있다 - Coredata -> iCloud로 변경하기 본문

오뚝이 개발자/SwiftUI

[iCloudKit 시리즈 3] 나도 백엔드 있다 - Coredata -> iCloud로 변경하기

rriver2 2024. 10. 1. 21:19
반응형

 🌷 iCloud 시리즈 목차 

1) iCloud 세팅과 개념 그리고 유저 연결하기

2.1) iCloud CRUD 해보기

2.2) 이미지, 비디오, 오디오 CRUD하기

3) Coredata -> iCloud로 변경하기

3) iCloud Noti 알아보기

4) 여러 에러나 마주했던 문제 상황들 ...


 

CoreData에서 iCloudKit으로 변경하는 방법...

생각보다 너무 쉬워서 놀랬던 !!

본 포스팅은 Setting Up Core Data with CloudKit을 참고해서 작성했습니다 !

 

Setting Up Core Data with CloudKit | Apple Developer Documentation

Set up the classes and capabilities that sync your store to CloudKit.

developer.apple.com

 

우선 프로젝트에 CoreData를 지원하고, 이를 이용해서 CRUD를 한 것은 이미 구현이 되어 있다고 가정하고 시작합니다. 만약 CoreData를 지원하려면 아래 링크를 확인해주세요.

 

Setting up a Core Data stack | Apple Developer Documentation

Set up the classes that manage and persist your app’s objects.

developer.apple.com


 🌷Core data를 iCloud로..!! 

1️⃣ iCloud 활성화

2️⃣ Enable CloudKit and push notifications

아래와 같은 방법으로 iCloud를 추가한다. 만약 Capability에서 iCloud가 뜨지 않는다면 Xcode가 개발자 계정으로 열려있는지 확인하길 !

iCloud를 추가하고 나면 아래와 같이 iCloud 섹션이 생겨난다. 이때 Containers 영역에 Container를 추가하면 되는데 이때 만든 Container는 내가 만든 여러 앱들 사이에서 데이터 공유가 가능해진다! 그리고 이유는 모르겠으나, 한번 만든 Container는 삭제가 안된다고 하더라구요?? ( 숨기기는 가능 ) 그러니 test를 하더라도 이름 깔쌈하게 지으시길 바랍니다 ㅋㅋㅋ !

 

3️⃣ Enable Remote notifications in the background

CloudKit에서 경고, 소리, 배지와 같은 사용자 알림을 표시하지 않고도 새로운 콘텐츠가 있을 때 앱에 자동으로 알리려면 원격 알림 백그라운드 모드를 활성화해야 한다.

 

4️⃣ 기존 Xcode 프로젝트 업데이트

이미 Core Data를 사용하는 앱에 CloudKit을 사용하여 Core Data를 추가하려면 프로젝트 구성과 일부 코드를 수정해야 한다. 

NSPersistentContainer로컬 영구 저장소만 지원하기 때문에 로컬 저장소를 CloudKit 데이터베이스에 동기화하는 기능을 추가하려면 NSPersistentContainerNSPersistentCloudKitContainer로 변경해야 한다.

init(inMemory: Bool = false) {
    // container = NSPersistentContainer(name: "Earthquakes") 
    // -> NSPersistentContainer을 NSPersistentCloudKitContainer으로 변경
    container = NSPersistentCloudKitContainer(name: "Earthquakes") 
    
    // 추가적으로 원한다면,
    // NSMergeByPropertyObjectTrumpMergePolicy는 코어 데이터가 로컬, 클라우드 두 곳에서 관리 되므로 충돌이 일어날 경우 로컬의 값을 우선으로 하는 정책
    container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
    
    if inMemory {
        container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
    }
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    // 추가적으로 원한다면,
    // automaticallyMergesChangesFromParent는 부모 컨텍스트의 변경사항을 자동으로 UI에 반영해주는 역할
    container.viewContext.automaticallyMergesChangesFromParent = true
}

 

5️⃣ 여러 stores 관리

 

6️⃣ 모든 프로퍼티와 릴레이션은 optional이어야 한다.

참고 ) WWDC 24 Core Data 스키마 개선

 

Core Data 스키마 개선 - WWDC22 - 비디오 - Apple Developer

앱을 업데이트한 후 Core Data 스키마를 깔끔하게 마이그레이션하고 데이터 모델 변경을 간편하게 수행하는 방법을 알아보세요. 내장된 마이그레이션 도구를 활용하여 데이터 저장 공간을 최신

developer.apple.com

 

7️⃣ 실 기기 2개로 확인하기

두 기기 모두 동일한 iCloud로 로그인이 되어 있어야 한다.

 

if ) 만약 cloudkit 다시 덜어내려면 NSPersistentHistoryTrackingKey 활성화를 다시 해야하기 때문에 코드를 아래와 같이 수정해야 한다. 

class CoreDataManager {
    
    static let instance = CoreDataManager()
    let container: NSPersistentContainer
    let context: NSManagedObjectContext
    
    init() {
        container = NSPersistentContainer(name: "TimelineContainer")
        
        // Persistent Store Description 설정
        if let description = container.persistentStoreDescriptions.first {
            // NSPersistentHistoryTrackingKey 활성화
            description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
            
            // 마이그레이션 옵션 설정
            let options: [String: Any] = [
                NSMigratePersistentStoresAutomaticallyOption: true,
                NSInferMappingModelAutomaticallyOption: true
            ]
        }
        
        container.loadPersistentStores { (description, error) in
            if let error = error {
                print("Error loading Core Data. \(error)")
            }
        }
        
        context = container.viewContext
    }
    
    ... 코드들
}

 

아니면 여기 Save 할 때 크래시 나요...

    func save() {
        do {
            try context.save()
            print("Saved successfully!")
        } catch let error {
            print("Error saving Core Data. \(error.localizedDescription)")
        }
    }

 🌷 참고 

https://developer.apple.com/documentation/cloudkit/enabling_cloudkit_in_your_app#//apple_ref/doc/uid/TP40014987-CH2

 

Enabling CloudKit in Your App | Apple Developer Documentation

Configure your app to store data in iCloud using CloudKit.

developer.apple.com

 

+) iCloud 디버깅하는 방법

https://developer.apple.com/documentation/coredata/mirroring_a_core_data_store_with_cloudkit/syncing_a_core_data_store_with_cloudkit

 

Syncing a Core Data Store with CloudKit | Apple Developer Documentation

Synchronize objects between devices, and handle store changes in the user interface.

developer.apple.com

 

반응형
Comments