iOS -一些常用的方法

时间:2021-10-18 10:04:19

1、获取本地的语言

  1. + (NSString *)getLocalLanguage
  2. {
  3. NSString *language = [[[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"] objectAtIndex:0];
  4. return language;
  5. }

2、获取Mac地址

  1. // returns the local MAC address.
  2. + (NSString*) macAddress:(NSString*)interfaceNameOrNil
  3. {
  4. // uses en0 as the default interface name
  5. NSString* interfaceName = interfaceNameOrNil;
  6. if (interfaceName == nil)
  7. {
  8. interfaceName = @"en0";
  9. }
  10. int                 mib[6];
  11. size_t              len;
  12. char                *buf;
  13. unsigned char       *ptr;
  14. struct if_msghdr    *ifm;
  15. struct sockaddr_dl  *sdl;
  16. mib[0] = CTL_NET;
  17. mib[1] = AF_ROUTE;
  18. mib[2] = 0;
  19. mib[3] = AF_LINK;
  20. mib[4] = NET_RT_IFLIST;
  21. if ((mib[5] = if_nametoindex([interfaceName UTF8String])) == 0)
  22. {
  23. printf("Error: if_nametoindex error\n");
  24. return NULL;
  25. }
  26. if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0)
  27. {
  28. printf("Error: sysctl, take 1\n");
  29. return NULL;
  30. }
  31. if ((buf = malloc(len)) == NULL)
  32. {
  33. printf("Could not allocate memory. error!\n");
  34. return NULL;
  35. }
  36. if (sysctl(mib, 6, buf, &len, NULL, 0) < 0)
  37. {
  38. printf("Error: sysctl, take 2");
  39. free(buf);
  40. return NULL;
  41. }
  42. ifm = (struct if_msghdr*) buf;
  43. sdl = (struct sockaddr_dl*) (ifm + 1);
  44. ptr = (unsigned char*) LLADDR(sdl);
  45. NSString *outstring = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",
  46. *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
  47. free(buf);
  48. return outstring;
  49. }

3、微博中获取时间差,(几天前,几小时前,几分钟前)

  1. + (NSString *) getTimeDiffString:(NSTimeInterval) timestamp
  2. {
  3. NSCalendar *cal = [NSCalendar currentCalendar];
  4. NSDate *todate = [NSDate dateWithTimeIntervalSince1970:timestamp];
  5. NSDate *today = [NSDate date];//当前时间
  6. unsigned int unitFlag = NSDayCalendarUnit | NSHourCalendarUnit |NSMinuteCalendarUnit;
  7. NSDateComponents *gap = [cal components:unitFlag fromDate:today toDate:todate options:0];//计算时间差
  8. if (ABS([gap day]) > 0)
  9. {
  10. return [NSString stringWithFormat:@"%d天前", ABS([gap day])];
  11. }else if(ABS([gap hour]) > 0)
  12. {
  13. return [NSString stringWithFormat:@"%d小时前", ABS([gap hour])];
  14. }else
  15. {
  16. return [NSString stringWithFormat:@"%d分钟前",  ABS([gap minute])];
  17. }
  18. }

4、计算字符串中单词的个数

  1. + (int)countWords:(NSString*)s
  2. {
  3. int i,n=[s length],l=0,a=0,b=0;
  4. unichar c;
  5. for(i=0;i<n;i++){
  6. c=[s characterAtIndex:i];
  7. if(isblank(c))
  8. {
  9. b++;
  10. }else if(isascii(c))
  11. {
  12. a++;
  13. }else
  14. {
  15. l++;
  16. }
  17. }
  18. if(a==0 && l==0)
  19. {
  20. return 0;
  21. }
  22. return l+(int)ceilf((float)(a+b)/2.0);
  23. }

5、屏幕截图并保存到相册

  1. + (UIImage*)saveImageFromView:(UIView*)view
  2. {
  3. UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, view.layer.contentsScale);
  4. [view.layer renderInContext:UIGraphicsGetCurrentContext()];
  5. UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  6. UIGraphicsEndImageContext();
  7. return image;
  8. }
  9. + (void)savePhotosAlbum:(UIImage *)image
  10. {
  11. UIImageWriteToSavedPhotosAlbum(image, self, @selector(imageSavedToPhotosAlbum: didFinishSavingWithError: contextInfo:), nil);
  12. }
  13. + (void)saveImageFromToPhotosAlbum:(UIView*)view
  14. {
  15. UIImage *image = [self saveImageFromView:view];
  16. [self savePhotosAlbum:image];
  17. }
  18. - (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *) contextInfo
  19. {
  20. NSString *message;
  21. NSString *title;
  22. if (!error) {
  23. title = @"成功提示";
  24. message = @"成功保存到相";
  25. } else {
  26. title = @"失败提示";
  27. message = [error description];
  28. }
  29. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
  30. message:message
  31. delegate:nil
  32. cancelButtonTitle:@"知道了"
  33. otherButtonTitles:nil];
  34. [alert show];
  35. [alert release];
  36. }

5、获取本月,本周,本季度第一天的时间戳

  1. + (unsigned long long)getFirstDayOfWeek:(unsigned long long)timestamp
  2. {
  3. NSDate *now = [NSDate dateWithTimeIntervalSince1970:timestamp];
  4. NSCalendar *cal = [NSCalendar currentCalendar];
  5. NSDateComponents *comps = [cal
  6. components:NSYearCalendarUnit| NSMonthCalendarUnit| NSWeekCalendarUnit | NSWeekdayCalendarUnit |NSWeekdayOrdinalCalendarUnit
  7. fromDate:now];
  8. if (comps.weekday <2)
  9. {
  10. comps.week = comps.week-1;
  11. }
  12. comps.weekday = 2;
  13. NSDate *firstDay = [cal dateFromComponents:comps];
  14. return [firstDay timeIntervalSince1970];
  15. }
  16. + (unsigned long long)getFirstDayOfQuarter:(unsigned long long)timestamp
  17. {
  18. NSDate *now = [NSDate dateWithTimeIntervalSince1970:timestamp];
  19. NSCalendar *cal = [NSCalendar currentCalendar];
  20. NSDateComponents *comps = [cal
  21. components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
  22. fromDate:now];
  23. if (comps.month <=3)
  24. {
  25. comps.month =  1;
  26. }
  27. else if(comps.month<=6)
  28. {
  29. comps.month =  4;
  30. }
  31. else if(comps.month<=9)
  32. {
  33. comps.month =  7;
  34. }
  35. else if(comps.month<=12)
  36. {
  37. comps.month =  10;
  38. }
  39. comps.day = 1;
  40. NSDate *firstDay = [cal dateFromComponents:comps];
  41. return [firstDay timeIntervalSince1970]*1000;
  42. }
  43. + (unsigned long long)getFirstDayOfMonth:(unsigned long long)timestamp
  44. {
  45. NSDate *now = [NSDate dateWithTimeIntervalSince1970:timestamp/1000];
  46. NSCalendar *cal = [NSCalendar currentCalendar];
  47. NSDateComponents *comps = [cal
  48. components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
  49. fromDate:now];
  50. comps.day = 1;
  51. NSDate *firstDay = [cal dateFromComponents:comps];
  52. return [firstDay timeIntervalSince1970]*1000;
  53. }

6、判断是否越狱

  1. static const char * __jb_app = NULL;
  2. + (BOOL)isJailBroken
  3. {
  4. static const char * __jb_apps[] =
  5. {
  6. "/Application/Cydia.app",
  7. "/Application/limera1n.app",
  8. "/Application/greenpois0n.app",
  9. "/Application/blackra1n.app",
  10. "/Application/blacksn0w.app",
  11. "/Application/redsn0w.app",
  12. NULL
  13. };
  14. __jb_app = NULL;
  15. // method 1
  16. for ( int i = 0; __jb_apps[i]; ++i )
  17. {
  18. if ( [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithUTF8String:__jb_apps[i]]] )
  19. {
  20. __jb_app = __jb_apps[i];
  21. return YES;
  22. }
  23. }
  24. // method 2
  25. if ( [[NSFileManager defaultManager] fileExistsAtPath:@"/private/var/lib/apt/"] )
  26. {
  27. return YES;
  28. }
  29. // method 3
  30. if ( 0 == system("ls") )
  31. {
  32. return YES;
  33. }
  34. return NO;
  35. }
  36. + (NSString *)jailBreaker
  37. {
  38. if ( __jb_app )
  39. {
  40. return [NSString stringWithUTF8String:__jb_app];
  41. }
  42. else
  43. {
  44. return @"";
  45. }
  46. }

7、定义单例的宏

  1. #undef  AS_SINGLETON
  2. #define AS_SINGLETON( __class ) \
  3. + (__class *)sharedInstance;
  4. #undef  DEF_SINGLETON
  5. #define DEF_SINGLETON( __class ) \
  6. + (__class *)sharedInstance \
  7. { \
  8. static dispatch_once_t once; \
  9. static __class * __singleton__; \
  10. dispatch_once( &once, ^{ __singleton__ = [[__class alloc] init]; } ); \
  11. return __singleton__; \
  12. }

8、网络状态检测

  1. - (void)reachabilityChanged:(NSNotification *)note {
  2. Reachability* curReach = [note object];
  3. NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
  4. NetworkStatus status = [curReach currentReachabilityStatus];
  5. if (status == NotReachable)
  6. {
  7. }
  8. else if(status == kReachableViaWiFi)
  9. {
  10. }
  11. else if(status == kReachableViaWWAN)
  12. {
  13. }
  14. }
  15. - (void)setNetworkNotification
  16. {
  17. [[NSNotificationCenter defaultCenter] addObserver:self
  18. selector:@selector(reachabilityChanged:)
  19. name: kReachabilityChangedNotification
  20. object: nil];
  21. _hostReach = [[Reachability reachabilityWithHostName:@"http://www.baidu.com"] retain];
  22. [_hostReach startNotifier];
  23. }

9、添加推送消息

  1. - (void)setPushNotification
  2. {
  3. [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound];
  4. }
  5. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  6. NSLog(@"获取设备的deviceToken: %@", deviceToken);
  7. }
  8. - (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error{
  9. NSLog(@"Failed to get token, error: %@", error);
  10. }

10、16进制颜色转UIColor

    1. + (UIColor *)colorWithHex:(NSString *)hex {
    2. // Remove `#` and `0x`
    3. if ([hex hasPrefix:@"#"]) {
    4. hex = [hex substringFromIndex:1];
    5. } else if ([hex hasPrefix:@"0x"]) {
    6. hex = [hex substringFromIndex:2];
    7. }
    8. // Invalid if not 3, 6, or 8 characters
    9. NSUInteger length = [hex length];
    10. if (length != 3 && length != 6 && length != 8) {
    11. return nil;
    12. }
    13. // Make the string 8 characters long for easier parsing
    14. if (length == 3) {
    15. NSString *r = [hex substringWithRange:NSMakeRange(0, 1)];
    16. NSString *g = [hex substringWithRange:NSMakeRange(1, 1)];
    17. NSString *b = [hex substringWithRange:NSMakeRange(2, 1)];
    18. hex = [NSString stringWithFormat:@"%@%@%@%@%@%@ff",
    19. r, r, g, g, b, b];
    20. } else if (length == 6) {
    21. hex = [hex stringByAppendingString:@"ff"];
    22. }
    23. CGFloat red = [[hex substringWithRange:NSMakeRange(0, 2)] _hexValue] / 255.0f;
    24. CGFloat green = [[hex substringWithRange:NSMakeRange(2, 2)] _hexValue] / 255.0f;
    25. CGFloat blue = [[hex substringWithRange:NSMakeRange(4, 2)] _hexValue] / 255.0f;
    26. CGFloat alpha = [[hex substringWithRange:NSMakeRange(6, 2)] _hexValue] / 255.0f;
    27. return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
    28. }