Skip to content

Instantly share code, notes, and snippets.

@trawor
Created June 23, 2013 02:27
Show Gist options
  • Save trawor/5843485 to your computer and use it in GitHub Desktop.
Save trawor/5843485 to your computer and use it in GitHub Desktop.
获取国内手机号运营商
/** 获取国内手机号运营商
* @param phone 手机号
* @return `U`是联通,`M`是移动,`T`是电信
*/
+(NSString*)carrierOfPhone:(NSString*)phone{
if (phone.length>11) {
//去掉乱七八糟的字符
phone=[[phone componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"+- "]] componentsJoinedByString:@""];
//如果86开头 去掉
if ([phone hasPrefix:@"86"]) phone=[phone substringFromIndex:2];
}else if(phone.length<11)
return nil;
NSString *regstring;
NSRegularExpression *regex;
NSTextCheckingResult *result;
regstring=@"1(\\d)(\\d)\\d{8}";
regex= [NSRegularExpression regularExpressionWithPattern:regstring options:0 error:NULL];
result=[regex firstMatchInString:phone options:0 range:NSMakeRange(0, phone.length)];
if (result) {
NSString *cu=@"U";
NSString *cm=@"M";
NSString *ct=@"T";
@try {
//捕获的第二位数
int n2=[[phone substringWithRange:[result rangeAtIndex:1]] intValue];
//捕获的第三位数
int n3=[[phone substringWithRange:[result rangeAtIndex:2]] intValue];
switch (n2) {
case 3:
switch (n3) {
case 0:
case 1:
case 2:
return cu;
case 3:return ct;
default:return cm;
}
break;
case 5:
switch (n3) {
case 3: return ct;
case 4: return nil;
case 6: return cu;
default:return cm;
}
break;
case 8:
switch (n3) {
case 0:
case 9:
return ct;
case 5:
case 6:
return cu;
case 7:
case 8:
return cm;
default:return nil;
}
break;
}
}
@catch (NSException *exception) {
}
}
return nil;
}
@nonstriater
Copy link

你这个太麻烦,可以看下这个:

  • (NSUInteger) carrierType
    {
    Class TeleNetInfo = NSClassFromString(@"CTTelephonyNetworkInfo");
    CTTelephonyNetworkInfo * info = [[TeleNetInfo alloc] init];
    CTCarrier * carrier = [info subscriberCellularProvider];
    [info release];

    if(carrier == nil)
    {
    return UIDeviceCarrierUnknown;
    }

    if(![[carrier mobileCountryCode] isEqualToString:@"460"])
    {
    return UIDeviceCarrierUnknown;
    }

    int carrierNetworkCode = [[carrier mobileNetworkCode] intValue];
    switch(carrierNetworkCode)
    {
    case 00: case 02: case 07:
    return UIDeviceCarrierChinaMobile;
    break;

        case 01: case 06:
            return UIDeviceCarrierChinaUnicom;
            break;
    
        case 03: case 05:
            return UIDeviceCarrierChinaTelecom;
            break;
    
        default:
            return UIDeviceCarrierUnknown;
            break;
    

    }

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment