I made a function that extracts a user name from the device name.

The idea is to skip setup steps to allow the user to go straight to play upon starting the app the first time.

This is a sub-optimal approach, as I can never trust the device name to hold the name of the user. The question is: What is a better way to do this?

My function below gets the right name ...

  • ... if the default name of the device has not changed ("Sanna's iPod")
  • ... in English,
  • ... in French and similar ("iPod de Sanna")
  • ... in Swedish and similar ("Sannas iPod") if the name does not end with S ("Johannes iPod" => returns "Johanne" but should rather return "Johannes" to be correct, as the name itself ends with an S.)

It obviously does not get the name right if the user has changed the name of the device to something else than the default form.

- (NSString *) extractPlayerNameFromDeviceName: (NSString *) deviceName  {

    // get words in device name
    NSArray *words = [deviceName componentsSeparatedByString:@" "];
    NSMutableArray *substrings = [[NSMutableArray alloc] init]; 
    for (NSString *word in words) {
        NSArray *subwords = [word componentsSeparatedByString:@"'"];
        [substrings addObjectsFromArray:subwords];
    }

    // find the name part of the device name
    NSString *playerName = [NSString stringWithString: @""];
    for (NSString *word in substrings) {
        if ([word compare:@"iPhone"] != 0
            && [word compare:@"iPod"] != 0
            && [word compare:@"iPad"] != 0
            && [word length] > 2) {
            playerName = word;
        }
    }

    // remove genitive
    unichar lastChar = [playerName characterAtIndex:[playerName length] - 1];
    if (lastChar == 's') {
        playerName = [playerName substringToIndex:[playerName length] - 1];
    }
    
ios
Edit
Report