如何获取iPhone的设备名称

172

如果你打开 设置 -> 通用 -> 关于本机,屏幕顶部会显示Bob的iPhone。如何在程序中获取这个名字?

12个回答

222

2
请注意:该链接中的教程非常有用,但是它面向OS 2.2,并使用一些在3.0中已被弃用的方法。 - Tim
@Tim:您完全正确。我没有考虑到那一点。不过,我并不是在建议教程;我只是提供了我的信息来源以及更多信息的来源。 - Frank V
@FrankV 我应该向用户请求哪些权限,以便让我的音乐应用程序更改他的iPhone名称?我该如何在Swift中实现这一点?谢谢。 - bibscy

182

除了上面的答案外,这是实际代码:

[[UIDevice currentDevice] name];


注:该代码是Objective-C语言中获取设备名称的方法调用。

110

记住:import UIKit

Swift:

UIDevice.currentDevice().name

Swift 3,4,5:

UIDevice.current.name

3
必须引入UIKit。 - DrWhat
Swift 5.1: UIDevice.current.nameSwift 5.1:UIDevice.current.name - Richard Witherspoon
是的,在Swift 5中,UIDevice.current.name对我有用。同样,我可以使用.model .batteryLevel等属性。谢谢! - marika.daboja
UIDevice.current.name在iOS16(beta3)下无法工作。 - Uthen

14

这是UIDevice的类结构

+ (UIDevice *)currentDevice;

@property(nonatomic,readonly,strong) NSString    *name;              // e.g. "My iPhone"
@property(nonatomic,readonly,strong) NSString    *model;             // e.g. @"iPhone", @"iPod touch"
@property(nonatomic,readonly,strong) NSString    *localizedModel;    // localized version of model
@property(nonatomic,readonly,strong) NSString    *systemName;        // e.g. @"iOS"
@property(nonatomic,readonly,strong) NSString    *systemVersion;

10

使用以下代码适用于Swift 4.0及以上版本:

    let udid = UIDevice.current.identifierForVendor?.uuidString
    let name = UIDevice.current.name
    let version = UIDevice.current.systemVersion
    let modelName = UIDevice.current.model
    let osName = UIDevice.current.systemName
    let localized = UIDevice.current.localizedModel
    
    print(udid ?? "") // ABCDEF01-0123-ABCD-0123-ABCDEF012345
    print(name)       // Name's iPhone
    print(version)    // 14.5
    print(modelName)  // iPhone
    print(osName)     // iOS
    print(localized)  // iPhone

1
这太棒了。非常有帮助。 - Krutika Sonawala
2
UIDevice.current.name在iOS16(beta3)下无法使用,苹果又进行了更改。 - Uthen

8

6
对于使用 Xamarin 的用户,请使用以下方法:
UIKit.UIDevice.CurrentDevice.Name

感谢您。对于Swift 3:UIDevice.current.name - Siddhartha Chikatamalla

6

对于Swift 4+版本,请使用以下代码:

UIDevice.current.name

4

4
以编程方式获取iPhone设备名称
 UIDevice *deviceInfo = [UIDevice currentDevice];

 NSLog(@"Device name:  %@", deviceInfo.name); 

// 设备名称: 我的iPod


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接