我创建了一个从设备名称中提取用户名的函数.
我们的想法是跳过设置步骤,以允许用户在第一次启动应用程序时直接进行游戏.
这是次优的方法,因为我永远不会相信设备名称来保存用户的名称.问题是:有什么更好的方法可以做到这一点?
我的下面的功能得到了正确的名字......
如果用户已将设备名称更改为默认表单以外的其他名称,则显然无法使名称正确.
- (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];
}
lastChar = [playerName characterAtIndex:[playerName length] - 1];
if (lastChar == '\'') {
playerName = [playerName substringToIndex:[playerName length] - 1];
}
return playerName;
}
Run Code Online (Sandbox Code Playgroud)
我用它来建议我的应用程序中的用户名.这样,大多数用户就不必费心编写用户名.
我的应用程序未连接到任何其他服务,如iTunes或Facebook,但每个用户都需要一个用户名.那我怎么得到名字?
我想对Ricky Helegesson的答案进行改进.它具有以下功能;
这是代码:
NSArray * nameFromDeviceName(NSString * deviceName)
{
NSError * error;
static NSString * expression = (@"^(?:iPhone|phone|iPad|iPod)\\s+(?:de\\s+)?|"
"(\\S+?)(?:['’]?s)?(?:\\s+(?:iPhone|phone|iPad|iPod))?$|"
"(\\S+?)(?:['’]??)?(?:\\s*(?:iPhone|phone|iPad|iPod))?$|"
"(\\S+)\\s+");
static NSRange RangeNotFound = (NSRange){.location=NSNotFound, .length=0};
NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern:expression
options:(NSRegularExpressionCaseInsensitive)
error:&error];
NSMutableArray * name = [NSMutableArray new];
for (NSTextCheckingResult * result in [regex matchesInString:deviceName
options:0
range:NSMakeRange(0, deviceName.length)]) {
for (int i = 1; i < result.numberOfRanges; i++) {
if (! NSEqualRanges([result rangeAtIndex:i], RangeNotFound)) {
[name addObject:[deviceName substringWithRange:[result rangeAtIndex:i]].capitalizedString];
}
}
}
return name;
}
Run Code Online (Sandbox Code Playgroud)
用它来返回一个名字;
NSString* name = [nameFromDeviceName(UIDevice.currentDevice.name) componentsJoinedByString:@" "];
Run Code Online (Sandbox Code Playgroud)
这有点复杂,所以我会解释;
如果一个名字以"s"结尾而没有"iPad"之前的撇号,我不会试图改变它,因为没有万无一失的方法来确定"s"是否是名称的一部分或者是多元化的名字.
请享用!
如果它只适用于 iPod 和 iPhone,那为什么还要使用用户名呢?如果您需要识别网络服务的设备,则每个设备还有其他唯一值(例如 UDID)。另一种选择是让用户从地址簿中选择代表自己的联系人并使用该数据。
| 归档时间: |
|
| 查看次数: |
8526 次 |
| 最近记录: |