문서 메뉴
문서 홈
/ /
Atlas Device SDK
/ /

Realm 구성 및 열기 - SwiftUI

이 페이지의 내용

  • 구성으로 Realm 열기
  • 동기화된 Realm 열기
  • 동기화된 Realm을 열기 전에 변경 사항 다운로드
  • 오프라인으로 동기화된 Realm 열기

Swift SDK는 SwiftUI 친화적인 방식으로 Realm을 열 수 있는 속성 래퍼를 제공합니다.

다음을 수행할 수 있습니다.

  • defaultConfiguration 를 사용 하여 영역을 암시적으로 열거 나 다른 구성을 지정합니다. 이는 동기화되지 않은 Realm과 동기화된 Realm 모두에서 작동합니다.

  • 사용자가 오프라인 상태일 때 시간이 초과되는 동기화된 Realm을 열기 전에 항상 변경 사항을 다운로드 합니다.

  • 사용자가 오프라인 상태일 때도 동기화된 Realm을 엽니다. Realm에 가장 최근 데이터가 부족할 수 있습니다.

@ObservedRealmObject 또는 @ObservedResults 를 사용하는 경우 이러한 속성 래퍼는 암시적으로 Realm을 열고 지정된 객체 또는 결과를 검색합니다.

// Implicitly use the default realm's objects(Dog.self)
@ObservedResults(Dog.self) var dogs

참고

@ObservedResults 속성 래퍼는 SwiftUI 보기에서 사용하기 위한 것입니다. View 모델에서 결과를 관찰하려면 변경 리스너를 등록하십시오.

구성을 지정하지 않으면 이러한 속성 래퍼는 defaultConfiguration 을 사용합니다. defaultConfiguration을 전역적으로 설정할 수 있으며, 앱 전체의 속성 래퍼가 Realm을 암시적으로 열 때 해당 구성을 사용할 수 있습니다.

속성 래퍼가 영역을 암시적으로 여는 데 사용하는 대체 구성을 제공할 수 있습니다. SyncConfiguration 과 로컬 구성 이 모두 있는 경우와 같이 앱에서 여러 구성을 사용할 때 이 작업을 수행할 수 있습니다. 이렇게 하려면 명시적 구성을 만듭니다. 그런 다음 환경 주입을 사용하여 해당 구성을 필요한 뷰에 전달합니다. 속성 래퍼가 영역을 여는 뷰에 구성을 전달하면 defaultConfiguration 대신 전달된 구성을 사용합니다.

버전 10.12.0의 새로운 기능

이러한 SwiftUI 속성 래퍼는 동기화된 Realm을 열고 뷰를 채웁니다. 이러한 속성 래퍼의 주요 차이점은 사용자가 온라인 상태여야 하는지 여부입니다.

  • Realm을 열기 전에 Atlas App Services 앱에서 업데이트를 다운로드하려면 @AsyncOpen 속성 래퍼를 사용합니다. 이를 위해서는 사용자가 네트워크에 연결되어 있어야 합니다.

  • 사용자가 네트워크에 연결되어 있는지 여부에 관계없이 동기화된 영역을 열려면 @AutoOpen 속성 래퍼를 사용합니다. 이 속성 래퍼를 사용하면 개발자가 앱에 오프라인 우선 기능을 설계할 수 있습니다.

Flexible Sync로 마이그레이션

Atlas App Services Device Sync 모드를 파티션 기반 동기화에서 Flexible Sync 로 자동 마이그레이션할 수 있습니다. 이를 통해 보다 표현력이 뛰어나고 세분화된 Flexible Sync 구독 및 권한을 활용하여 사용자가 읽고 쓸 수 있는 동기화된 데이터를 관리할 수 있습니다. 자세한 내용 은 파티션 기반 동기화에서 Flexible Sync로 마이그레이션을 참조하세요.

서버의 최신 정보가 필요한 앱(예: 사용자가 여러 기기에서 플레이할 수 있는 실시간 순위표가 있는 게임 앱)의 경우 @AsyncOpen 속성 래퍼를 사용하세요. 이렇게 하면 사용자가 오래된 데이터가 있는 앱을 사용하지 않도록 할 수 있습니다.

버전 10.27.0에 추가 되었습니다.

Realm Swift SDK 버전 10.27.0 는 속성 래퍼의 Flexible Sync 버전을 추가하여 SwiftUI로 Realm을 엽니다. Realm을 연 후 .onAppear 에서 구독 쿼리를 추가할 수 있습니다.

@AsyncOpen(appId: flexibleSyncAppId, timeout: 4000) var asyncOpen

버전 10.28.0의 새로운 기능

initialSubscriptions 매개변수를 사용하여 flexibleSyncConfiguration() 을 생성할 수 있습니다. 이 매개변수를 사용하여 구성에서 Flexible Sync 쿼리를 구독 할 수 있습니다. 예를 들어 정기적으로 다시 로드되는 뷰에 있는 경우와 같이 두 번 이상 실행되는 경우, 추가하기 전에 구독이 이미 존재하는지 확인합니다. 동일한 구독을 다시 추가하면 오류가 발생합니다.

// Create a `flexibleSyncConfiguration` with `initialSubscriptions`.
// We'll inject this configuration as an environment value to use when opening the realm
// in the next view, and the realm will open with these initial subscriptions.
let config = user.flexibleSyncConfiguration(initialSubscriptions: { subs in
let peopleSubscriptionExists = subs.first(named: "people")
let dogSubscriptionExists = subs.first(named: "dogs")
// Check whether the subscription already exists. Adding it more
// than once causes an error.
if (peopleSubscriptionExists != nil) && (dogSubscriptionExists != nil) {
// Existing subscriptions found - do nothing
return
} else {
// Add queries for any objects you want to use in the app
// Linked objects do not automatically get queried, so you
// must explicitly query for all linked objects you want to include.
subs.append(QuerySubscription<Person>(name: "people"))
subs.append(QuerySubscription<Dog>(name: "dogs"))
}
})

그런 다음 속성 래퍼가 환경 객체로 포함된 뷰에 구성을 전달합니다.

OpenFlexibleSyncRealmView()
.environment(\.realmConfiguration, config)

전체 예제는 SwiftUI 빠른 시작을 참조하세요.

파티션 기반 동기화 를 사용하여 영역을 열려면 속성 래퍼에 partitionValue 를 추가합니다.

@AsyncOpen(appId: YOUR_APP_SERVICES_APP_ID_HERE, partitionValue: "", timeout: 4000) var asyncOpen

이 SwiftUI 속성 래퍼는 현재 사용자에 대해 Realm.asyncOpen() 를 시작합니다. 속성 래퍼는 뷰를 업데이트하는 데 사용할 수 있는 AsyncOpenState 열거형 으로 표시되는 상태를 게시합니다.

예제

이 예에서는 @AsyncOpen 를 사용하여 뷰에서 Realm을 여는 한 가지 방법을 보여 줍니다. 먼저 사용자를 확인하거나 로그인합니다. 그런 다음 Realm을 열려고 시도하고 AsyncOpenState 을 켜서 적절한 보기를 표시합니다. Realm이 성공적으로 열리면 이를 환경 값으로 삽입하여 뷰를 채웁니다.

/// This view opens a synced realm.
struct OpenFlexibleSyncRealmView: View {
// We've injected a `flexibleSyncConfiguration` as an environment value,
// so `@AsyncOpen` here opens a realm using that configuration.
@AsyncOpen(appId: flexibleSyncAppId, timeout: 4000) var asyncOpen
var body: some View {
switch asyncOpen {
// Starting the Realm.asyncOpen process.
// Show a progress view.
case .connecting:
ProgressView()
// Waiting for a user to be logged in before executing
// Realm.asyncOpen.
case .waitingForUser:
ProgressView("Waiting for user to log in...")
// The realm has been opened and is ready for use.
// Show the content view.
case .open(let realm):
// Do something with the realm
UseRealmView(realm: realm)
// The realm is currently being downloaded from the server.
// Show a progress view.
case .progress(let progress):
ProgressView(progress)
// Opening the Realm failed.
// Show an error view.
case .error(let error):
ErrorView(error: error)
}
}
}
/// This view opens a synced realm.
struct OpenPartitionBasedSyncRealm: View {
// @AsyncOpen attempts to connect to the server and download remote changes
// before the realm opens. If there is no network connection,
// AsyncOpen cannot load changes and the realm does not open.
// We can use an empty string as the partitionValue here because we're
// injecting the user.id as an environment value from the LoginView.
@AsyncOpen(appId: YOUR_APP_SERVICES_APP_ID_HERE, partitionValue: "", timeout: 4000) var asyncOpen
var body: some View {
switch asyncOpen {
// Starting the Realm.asyncOpen process.
// Show a progress view.
case .connecting:
ProgressView()
// Waiting for a user to be logged in before executing
// Realm.asyncOpen.
case .waitingForUser:
ProgressView("Waiting for user to log in...")
// The realm has been opened and is ready for use.
// Show the content view.
case .open(let realm):
// Do something with the realm
UseRealmView(realm: realm)
// The realm is currently being downloaded from the server.
// Show a progress view.
case .progress(let progress):
ProgressView(progress)
// Opening the Realm failed.
// Show an error view.
case .error(let error):
ErrorView(error: error)
}
}
}

@AsyncOpen 과 마찬가지로 @AutoOpen 은 Realm을 열기 전에 업데이트 다운로드를 시도합니다. 그러나 네트워크에 연결할 수 없는 경우 이 방법은 대신 장치의 데이터가 있는 Realm을 엽니다.

사용자가 기기의 데이터로 작업할 수 있어야 하는 메모 앱과 같이 사용자가 잠재적으로 오래된 데이터로 작업하는 데 문제가 없는 앱에 이 속성 래퍼를 사용합니다.

@AutoOpen(appId: "app_id") var autoOpen
@AutoOpen(appId: "app_id", partitionValue: <partition_value>) var autoOpen

이 SwiftUI 속성 래퍼는 현재 사용자의 Realm을 열기 전에 업데이트 다운로드를 시도합니다. 인터넷에 연결되어 있지 않은 경우 이 속성 래퍼는 지정된 appId 및 Flexible Sync 또는 파티션 기반 동기화 구성에 대한 로컬 Realm 파일의 최신 버전을 대신 반환합니다.

속성 래퍼는 뷰를 업데이트하는 데 사용할 수 있는 AsyncOpenState 열거형 으로 표시되는 상태를 게시합니다. 전체 예시는 위의 @AsyncOpen 코드 예시를 참조하세요.

돌아가기

객체 모델 변경

다음

변경 사항에 대한 반응