Dung Tran
Dung Tran

Reputation: 19

How to get the content of a notification in XCUITest?

How to get the content of a notification in XCUITest, specifically the notification's identifier

I have a piece of code in my app to show a notification as follows:

- (NSString *)showNotificationWithIdentifier:(NSString * _Nullable)identifier
                                        title:(NSString *)title
                                 description:(NSString *)description {
    NSString *_id;
    // No ID specified (automatic increment)
    if (identifier == nil) {
        NSUserDefaults *prefer = [[NSUserDefaults alloc] initWithSuiteName:AfibNotificationManager.TAG];
        NSString *latestIdStr = [prefer stringForKey:AfibNotificationManager.LATEST_ID_KEY];
        int tmpId;
        if (latestIdStr == nil) {
            tmpId = INT_MIN;
        } else {
            tmpId = [latestIdStr intValue];
            tmpId += 1;
        }
        _id = [NSString stringWithFormat:@"%d", tmpId];
        [prefer setValue:_id forKey:AfibNotificationManager.LATEST_ID_KEY];
    }
    // ID specified
    else {
        _id = identifier;
    }
    
    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    content.title = title;
    content.body = description;
    content.sound = [UNNotificationSound defaultSound];
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:_id content:content trigger:nil];
    dispatch_async(dispatch_get_main_queue(), ^{
        [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:nil];
    });
    
    return _id;
}

This is my UITest code:

- (void)checkNotification {
    
    XCUIApplication *app = [[XCUIApplication alloc] init];
    [app launch];
    [app.buttons[@"btn"] tap]; //click button will call method showNotificationWithIdentifier to show notification
    
    XCUIApplication *springboard = [[XCUIApplication alloc];
    initWithBundleIdentifier:@"com.apple.springboard"];
    XCUICoordinate *start = [app coordinateWithNormalizedOffset:CGVectorMake(0.5, 0.0)];
    XCUICoordinate *finish = [app coordinateWithNormalizedOffset:CGVectorMake(0.5, 1.5)];
    [start pressForDuration:0.1 thenDragToCoordinate:finish];
    XCUIElement *notification = springboard.buttons[@"NotificationCell"];
    XCTAssertTrue([notification waitForExistenceWithTimeout:5]);
    NSString *identifier = notification.identifier;
}

When I perform XCUITest to get notification information such as notification identifier, I encounter difficulties and it seems incorrect. Could you help me with a way to retrieve the notification identifier, label, and check if the notification has been displayed or not? Thank you.

Upvotes: 0

Views: 36

Answers (0)

Related Questions