Skip to content

Commit f7a70a9

Browse files
committed
Update custom user data examples
1 parent dd5e608 commit f7a70a9

10 files changed

+270
-43
lines changed
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
#import <XCTest/XCTest.h>
2+
#import <Realm/Realm.h>
3+
#import "MyRealmApp.h"
4+
5+
@interface CustomUserData : XCTestCase
6+
7+
@end
8+
9+
@implementation CustomUserData
10+
11+
- (void)testCreateCustomUserData {
12+
XCTestExpectation *expectation = [self expectationWithDescription:@"it completes"];
13+
14+
// :code-block-start: create-custom-user-data
15+
RLMApp *app = [RLMApp appWithId:YOUR_REALM_APP_ID];
16+
[app loginWithCredential:[RLMCredentials anonymousCredentials] completion:^(RLMUser *user, NSError *error) {
17+
if (error != nil) {
18+
NSLog(@"Failed to log in: %@", error);
19+
return;
20+
}
21+
RLMMongoClient *client = [user mongoClientWithServiceName:@"mongodb-atlas"];
22+
RLMMongoDatabase *database = [client databaseWithName:@"my_database"];
23+
RLMMongoCollection *collection = [database collectionWithName:@"users"];
24+
[collection insertOneDocument:
25+
@{@"userId": [user identifier], @"favoriteColor": @"pink"}
26+
completion:^(RLMObjectId *newObjectId, NSError *error) {
27+
if (error != nil) {
28+
NSLog(@"Failed to insert: %@", error);
29+
// :hide-start:
30+
XCTAssertEqualObjects([error localizedDescription], @"no rule exists for namespace 'my_database.users'");
31+
[expectation fulfill];
32+
// :hide-end:
33+
}
34+
NSLog(@"Inserted custom user data document with object ID: %@", newObjectId);
35+
}];
36+
}];
37+
// :code-block-end:
38+
39+
[self waitForExpectationsWithTimeout:10 handler:^(NSError *error) {
40+
NSLog(@"Expectation failed: %@", error);
41+
}];
42+
}
43+
44+
- (void)testReadCustomUserData {
45+
XCTestExpectation *expectation = [self expectationWithDescription:@"it completes"];
46+
47+
// :code-block-start: read-custom-user-data
48+
RLMApp *app = [RLMApp appWithId:YOUR_REALM_APP_ID];
49+
[app loginWithCredential:[RLMCredentials anonymousCredentials] completion:^(RLMUser *user, NSError *error) {
50+
if (error != nil) {
51+
NSLog(@"Failed to log in: %@", error);
52+
return;
53+
}
54+
55+
// One way to use custom data:
56+
NSLog(@"User custom data: %@", [user customData]);
57+
58+
// Another way to use custom data: refresh in case the client-side data is stale
59+
[user refreshCustomDataWithCompletion:^(NSDictionary *customData, NSError *error) {
60+
if (error != nil) {
61+
NSLog(@"Failed to refresh custom user data: %@", error);
62+
return;
63+
}
64+
NSLog(@"Favorite color: %@", customData[@"favoriteColor"]);
65+
// :hide-start:
66+
[expectation fulfill];
67+
// :hide-end:
68+
}];
69+
}];
70+
// :code-block-end:
71+
72+
[self waitForExpectationsWithTimeout:10 handler:^(NSError *error) {
73+
NSLog(@"Expectation failed: %@", error);
74+
}];
75+
}
76+
77+
- (void)testUpdateCustomUserData {
78+
XCTestExpectation *expectation = [self expectationWithDescription:@"it completes"];
79+
80+
// :code-block-start: update-custom-user-data
81+
RLMApp *app = [RLMApp appWithId:YOUR_REALM_APP_ID];
82+
[app loginWithCredential:[RLMCredentials anonymousCredentials] completion:^(RLMUser *user, NSError *error) {
83+
if (error != nil) {
84+
NSLog(@"Failed to log in: %@", error);
85+
return;
86+
}
87+
RLMMongoClient *client = [user mongoClientWithServiceName:@"mongodb-atlas"];
88+
RLMMongoDatabase *database = [client databaseWithName:@"my_database"];
89+
RLMMongoCollection *collection = [database collectionWithName:@"users"];
90+
91+
// Update the user's custom data document
92+
[collection updateOneDocumentWhere:@{@"userId": [user identifier]}
93+
updateDocument: @{@"favoriteColor": @"cerulean"}
94+
completion:^(RLMUpdateResult *updateResult, NSError *error) {
95+
if (error != nil) {
96+
NSLog(@"Failed to insert: %@", error);
97+
// :hide-start:
98+
XCTAssertEqualObjects([error localizedDescription], @"no rule exists for namespace 'my_database.users'");
99+
[expectation fulfill];
100+
// :hide-end:
101+
}
102+
NSLog(@"Matched: %lu, modified: %lu", [updateResult matchedCount], [updateResult modifiedCount]);
103+
}];
104+
}];
105+
// :code-block-end:
106+
107+
[self waitForExpectationsWithTimeout:10 handler:^(NSError *error) {
108+
NSLog(@"Expectation failed: %@", error);
109+
}];
110+
}
111+
112+
@end
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
import XCTest
2+
import RealmSwift
3+
4+
class CustomUserData: XCTestCase {
5+
6+
func testCreateCustomUserData() {
7+
let expectation = XCTestExpectation(description: "it completes")
8+
9+
// :code-block-start: create-custom-user-data
10+
let appId = YOUR_REALM_APP_ID // replace this with your App ID
11+
let app = App(id: appId)
12+
app.login(credentials: Credentials.anonymous) { (user, error) in
13+
guard error == nil else {
14+
print("Failed to log in: \(error!.localizedDescription)")
15+
return
16+
}
17+
let client = user!.mongoClient("mongodb-atlas")
18+
let database = client.database(named: "my_database")
19+
let collection = database.collection(withName: "users")
20+
21+
// Insert the custom user data object
22+
collection.insertOne([
23+
"userId": AnyBSON(user!.id),
24+
"favoriteColor": "pink"
25+
]) { (newObjectId, error) in
26+
guard error == nil else {
27+
print("Failed to insert document: \(error!.localizedDescription)")
28+
// :hide-start:
29+
XCTAssertEqual(error!.localizedDescription, "no rule exists for namespace 'my_database.users'")
30+
expectation.fulfill()
31+
// :hide-end:
32+
return
33+
}
34+
print("Inserted custom user data document with object ID: \(newObjectId!)")
35+
}
36+
}
37+
// :code-block-end:
38+
wait(for: [expectation], timeout: 10)
39+
}
40+
41+
func testReadCustomUserData() {
42+
let expectation = XCTestExpectation(description: "it completes")
43+
44+
// :code-block-start: read-custom-user-data
45+
let appId = YOUR_REALM_APP_ID // replace this with your App ID
46+
let app = App(id: appId)
47+
app.login(credentials: Credentials.anonymous) { (user, error) in
48+
guard error == nil else {
49+
print("Failed to log in: \(error!.localizedDescription)")
50+
return
51+
}
52+
53+
// One way to use custom data:
54+
print("User custom data: \(user!.customData)")
55+
56+
// Another way: refresh in case the user data is stale.
57+
user!.refreshCustomData() { (customData, error) in
58+
guard error == nil else {
59+
print("Failed to refresh custom data: \(error!.localizedDescription)")
60+
return
61+
}
62+
guard let customData = customData else {
63+
// This may happen if no custom data was set for the user id.
64+
// It could also be caused by not having custom data enabled and
65+
// configured correctly!
66+
print("Custom data not set")
67+
return
68+
}
69+
// favoriteColor was set on the custom data.
70+
print("Favorite color: \(customData["favoriteColor"] ?? "not set")")
71+
// :hide-start:
72+
expectation.fulfill()
73+
// :hide-end:
74+
}
75+
}
76+
// :code-block-end:
77+
wait(for: [expectation], timeout: 10)
78+
}
79+
80+
func testUpdateCustomUserData() {
81+
let expectation = XCTestExpectation(description: "it completes")
82+
83+
// :code-block-start: update-custom-user-data
84+
let appId = YOUR_REALM_APP_ID // replace this with your App ID
85+
let app = App(id: appId)
86+
app.login(credentials: Credentials.anonymous) { (user, error) in
87+
guard error == nil else {
88+
print("Failed to log in: \(error!.localizedDescription)")
89+
return
90+
}
91+
92+
// Access the custom user document remotely to update it.
93+
let client = user!.mongoClient("mongodb-atlas")
94+
let database = client.database(named: "my_database")
95+
let collection = database.collection(withName: "users")
96+
collection.updateOneDocument(
97+
filter: ["userId": AnyBSON(user!.id)],
98+
update: ["favoriteColor": "cerulean"]
99+
) { (updateResult, error) in
100+
guard error == nil else {
101+
print("Failed to update: \(error!.localizedDescription)")
102+
// :hide-start:
103+
XCTAssertEqual(error!.localizedDescription, "no rule exists for namespace 'my_database.users'")
104+
expectation.fulfill()
105+
// :hide-end:
106+
return
107+
}
108+
109+
// User document updated.
110+
print("Matched: \(updateResult!.matchedCount), updated: \(updateResult!.modifiedCount)")
111+
}
112+
}
113+
// :code-block-end:
114+
wait(for: [expectation], timeout: 10)
115+
}
116+
117+
}

examples/ios/RealmExamples.xcodeproj/project.pbxproj

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@
2727
48C072062511B6DB004B02BB /* ManageEmailPasswordUsers.m in Sources */ = {isa = PBXBuildFile; fileRef = 48C072052511B6DB004B02BB /* ManageEmailPasswordUsers.m */; };
2828
48E63FB8252646A700F883B1 /* Authenticate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48E63FB7252646A700F883B1 /* Authenticate.swift */; };
2929
48F38B502527806600DDEB65 /* AccessMongoDB.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48F38B4F2527806600DDEB65 /* AccessMongoDB.swift */; };
30+
48F38B522527843B00DDEB65 /* CustomUserData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48F38B512527843B00DDEB65 /* CustomUserData.swift */; };
31+
48F38B5425278ECB00DDEB65 /* CustomUserData.m in Sources */ = {isa = PBXBuildFile; fileRef = 48F38B5325278ECB00DDEB65 /* CustomUserData.m */; };
3032
/* End PBXBuildFile section */
3133

3234
/* Begin PBXContainerItemProxy section */
@@ -67,6 +69,8 @@
6769
48C072052511B6DB004B02BB /* ManageEmailPasswordUsers.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ManageEmailPasswordUsers.m; sourceTree = "<group>"; };
6870
48E63FB7252646A700F883B1 /* Authenticate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Authenticate.swift; sourceTree = "<group>"; };
6971
48F38B4F2527806600DDEB65 /* AccessMongoDB.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccessMongoDB.swift; sourceTree = "<group>"; };
72+
48F38B512527843B00DDEB65 /* CustomUserData.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomUserData.swift; sourceTree = "<group>"; };
73+
48F38B5325278ECB00DDEB65 /* CustomUserData.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = CustomUserData.m; sourceTree = "<group>"; };
7074
4B040991139BCE878C9D6C0A /* Pods-RealmExamples.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RealmExamples.release.xcconfig"; path = "Target Support Files/Pods-RealmExamples/Pods-RealmExamples.release.xcconfig"; sourceTree = "<group>"; };
7175
68EA0F823D8002EF83FC15E5 /* Pods_RealmSwiftExampleTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RealmSwiftExampleTests.framework; sourceTree = BUILT_PRODUCTS_DIR; };
7276
6C55D4D8147A41A52A10E3EF /* Pods_RealmObjcExampleTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RealmObjcExampleTests.framework; sourceTree = BUILT_PRODUCTS_DIR; };
@@ -131,6 +135,8 @@
131135
48BF341C25111194004139AF /* Task.swift */,
132136
48924B892514EAD900CC9567 /* MultipleUsers.swift */,
133137
48F38B4F2527806600DDEB65 /* AccessMongoDB.swift */,
138+
48F38B512527843B00DDEB65 /* CustomUserData.swift */,
139+
48F38B5325278ECB00DDEB65 /* CustomUserData.m */,
134140
48924BBA2515309F00CC9567 /* MultipleUsers.m */,
135141
48E63FB7252646A700F883B1 /* Authenticate.swift */,
136142
48BF34172511095C004139AF /* RealmApp.swift */,
@@ -357,6 +363,7 @@
357363
4896EE58251051C800D1FABF /* ExampleObjcTestCase.m in Sources */,
358364
4896EE55251051A600D1FABF /* ExampleSwiftTestCase.swift in Sources */,
359365
48924BBB2515309F00CC9567 /* MultipleUsers.m in Sources */,
366+
48F38B5425278ECB00DDEB65 /* CustomUserData.m in Sources */,
360367
48924B8C2514FEFC00CC9567 /* TestSetup.swift in Sources */,
361368
48C072062511B6DB004B02BB /* ManageEmailPasswordUsers.m in Sources */,
362369
48BF34182511095C004139AF /* RealmApp.swift in Sources */,
@@ -366,6 +373,7 @@
366373
48F38B502527806600DDEB65 /* AccessMongoDB.swift in Sources */,
367374
48BF341F251129AD004139AF /* MyRealmApp.m in Sources */,
368375
48C072042511B5D5004B02BB /* ManageEmailPasswordUsers.swift in Sources */,
376+
48F38B522527843B00DDEB65 /* CustomUserData.swift in Sources */,
369377
);
370378
runOnlyForDeploymentPostprocessing = 0;
371379
};
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
RLMApp *app = [RLMApp appWithId:@"<YourAppId>"]; // replace this with your App ID
1+
RLMApp *app = [RLMApp appWithId:YOUR_REALM_APP_ID];
22
[app loginWithCredential:[RLMCredentials anonymousCredentials] completion:^(RLMUser *user, NSError *error) {
33
if (error != nil) {
44
NSLog(@"Failed to log in: %@", error);
@@ -8,11 +8,11 @@
88
RLMMongoDatabase *database = [client databaseWithName:@"my_database"];
99
RLMMongoCollection *collection = [database collectionWithName:@"users"];
1010
[collection insertOneDocument:
11-
@{@"userId": [user identity], @"favoriteColor": @"pink"}
11+
@{@"userId": [user identifier], @"favoriteColor": @"pink"}
1212
completion:^(RLMObjectId *newObjectId, NSError *error) {
1313
if (error != nil) {
1414
NSLog(@"Failed to insert: %@", error);
1515
}
1616
NSLog(@"Inserted custom user data document with object ID: %@", newObjectId);
1717
}];
18-
}];
18+
}];
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,17 @@
1-
let appId = "<YourAppId>" // replace this with your App ID
1+
let appId = YOUR_REALM_APP_ID // replace this with your App ID
22
let app = App(id: appId)
3-
app.login(credentials: Credentials.anonymous()) { (user, error) in
3+
app.login(credentials: Credentials.anonymous) { (user, error) in
44
guard error == nil else {
55
print("Failed to log in: \(error!.localizedDescription)")
66
return
77
}
8-
guard let user = user else {
9-
fatalError("User is nil without error")
10-
}
11-
let client = user.mongoClient("mongodb-atlas")
8+
let client = user!.mongoClient("mongodb-atlas")
129
let database = client.database(named: "my_database")
1310
let collection = database.collection(withName: "users")
1411

1512
// Insert the custom user data object
1613
collection.insertOne([
17-
"userId": AnyBSON(user.id!),
14+
"userId": AnyBSON(user!.id),
1815
"favoriteColor": "pink"
1916
]) { (newObjectId, error) in
2017
guard error == nil else {
@@ -23,4 +20,4 @@ app.login(credentials: Credentials.anonymous()) { (user, error) in
2320
}
2421
print("Inserted custom user data document with object ID: \(newObjectId!)")
2522
}
26-
}
23+
}

source/examples/CustomUserData/ReadCustomUserData.m renamed to source/examples/generated/code/start/CustomUserData.codeblock.read-custom-user-data.m

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
RLMApp *app = [RLMApp appWithId:@"<YourAppId>"]; // replace this with your App ID
1+
RLMApp *app = [RLMApp appWithId:YOUR_REALM_APP_ID];
22
[app loginWithCredential:[RLMCredentials anonymousCredentials] completion:^(RLMUser *user, NSError *error) {
33
if (error != nil) {
44
NSLog(@"Failed to log in: %@", error);
@@ -16,4 +16,4 @@
1616
}
1717
NSLog(@"Favorite color: %@", customData[@"favoriteColor"]);
1818
}];
19-
}];
19+
}];
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,16 @@
1-
let appId = "<YourAppId>" // replace this with your App ID
1+
let appId = YOUR_REALM_APP_ID // replace this with your App ID
22
let app = App(id: appId)
3-
app.login(credentials: Credentials.anonymous()) { (user, error) in
3+
app.login(credentials: Credentials.anonymous) { (user, error) in
44
guard error == nil else {
55
print("Failed to log in: \(error!.localizedDescription)")
66
return
77
}
8-
guard let user = user else {
9-
fatalError("User is nil without error")
10-
}
118

129
// One way to use custom data:
13-
print("User custom data: \(user.customData)")
10+
print("User custom data: \(user!.customData)")
1411

1512
// Another way: refresh in case the user data is stale.
16-
user.refreshCustomData() { (customData, error) in
13+
user!.refreshCustomData() { (customData, error) in
1714
guard error == nil else {
1815
print("Failed to refresh custom data: \(error!.localizedDescription)")
1916
return
@@ -26,6 +23,6 @@ app.login(credentials: Credentials.anonymous()) { (user, error) in
2623
return
2724
}
2825
// favoriteColor was set on the custom data.
29-
print("Favorite color: \(customData["favoriteColor"]!)")
26+
print("Favorite color: \(customData["favoriteColor"] ?? "not set")")
3027
}
31-
}
28+
}
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
RLMApp *app = [RLMApp appWithId:@"<YourAppId>"]; // replace this with your App ID
1+
RLMApp *app = [RLMApp appWithId:YOUR_REALM_APP_ID];
22
[app loginWithCredential:[RLMCredentials anonymousCredentials] completion:^(RLMUser *user, NSError *error) {
33
if (error != nil) {
44
NSLog(@"Failed to log in: %@", error);
@@ -9,12 +9,12 @@
99
RLMMongoCollection *collection = [database collectionWithName:@"users"];
1010

1111
// Update the user's custom data document
12-
[collection updateOneDocumentWhere:@{@"userId": [user identity]}
12+
[collection updateOneDocumentWhere:@{@"userId": [user identifier]}
1313
updateDocument: @{@"favoriteColor": @"cerulean"}
1414
completion:^(RLMUpdateResult *updateResult, NSError *error) {
1515
if (error != nil) {
1616
NSLog(@"Failed to insert: %@", error);
1717
}
1818
NSLog(@"Matched: %lu, modified: %lu", [updateResult matchedCount], [updateResult modifiedCount]);
1919
}];
20-
}];
20+
}];

0 commit comments

Comments
 (0)