我想检查设备的iOS版本是否大于3.1.3 我尝试了以下方法:
[[UIDevice currentDevice].systemVersion floatValue]
但是不管用,我只想要一个:
if (version > 3.1.3) { }
我怎样才能做到这一点呢?
我想检查设备的iOS版本是否大于3.1.3 我尝试了以下方法:
[[UIDevice currentDevice].systemVersion floatValue]
但是不管用,我只想要一个:
if (version > 3.1.3) { }
我怎样才能做到这一点呢?
当前回答
基本上和这个想法一样https://stackoverflow.com/a/19903595/1937908但更健壮:
#ifndef func_i_system_version_field
#define func_i_system_version_field
inline static int i_system_version_field(unsigned int fieldIndex) {
NSString* const versionString = UIDevice.currentDevice.systemVersion;
NSArray<NSString*>* const versionFields = [versionString componentsSeparatedByString:@"."];
if (fieldIndex < versionFields.count) {
NSString* const field = versionFields[fieldIndex];
return field.intValue;
}
NSLog(@"[WARNING] i_system_version(%iu): field index not present in version string '%@'.", fieldIndex, versionString);
return -1; // error indicator
}
#endif
只需将上面的代码放在一个头文件中。
用法:
int major = i_system_version_field(0);
int minor = i_system_version_field(1);
int patch = i_system_version_field(2);
其他回答
Try:
NSComparisonResult order = [[UIDevice currentDevice].systemVersion compare: @"3.1.3" options: NSNumericSearch];
if (order == NSOrderedSame || order == NSOrderedDescending) {
// OS version >= 3.1.3
} else {
// OS version < 3.1.3
}
+(BOOL)doesSystemVersionMeetRequirement:(NSString *)minRequirement{
// eg NSString *reqSysVer = @"4.0";
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
if ([currSysVer compare:minRequirement options:NSNumericSearch] != NSOrderedAscending)
{
return YES;
}else{
return NO;
}
}
试试这个
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
// do some work
}
所有的答案看起来都有点太大了。 我只用:
if (SYSTEM_VERSION_GREATER_THAN(@"7.0")){(..CODE...)}
if (SYSTEM_VERSION_EQUAL_TO(@"7.0")){(..CODE...)}
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")){(..CODE...)}
if (SYSTEM_VERSION_LESS_THAN(@"7.0")){(..CODE...)}
if (SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(@"7.0")){(..CODE...)}
当然,将@“7.0”替换为所需的操作系统版本。
在Swift中查看iOS版本的解决方案
switch (UIDevice.currentDevice().systemVersion.compare("8.0.0", options: NSStringCompareOptions.NumericSearch)) {
case .OrderedAscending:
println("iOS < 8.0")
case .OrderedSame, .OrderedDescending:
println("iOS >= 8.0")
}
这个解决方案的缺点:不管你用哪种方式检查OS版本号,这都是一种糟糕的做法。永远不要以这种方式硬编码依赖关系,总是检查特性、功能或类的存在。考虑这一切;苹果可能会发布一个类的向后兼容版本,如果他们这样做了,那么你建议的代码将永远不会使用它,因为你的逻辑是寻找操作系统版本号,而不是类的存在。
(信息来源)
在Swift中检查类存在的解决方案
if (objc_getClass("UIAlertController") == nil) {
// iOS 7
} else {
// iOS 8+
}
不要使用if (NSClassFromString("UIAlertController") == nil),因为它在使用iOS 7.1和8.2的iOS模拟器上正常工作,但如果你在使用iOS 7.1的真实设备上测试,你会不幸地注意到你永远不会通过代码片段的else部分。