gpt4 book ai didi

iOS常用的公共方法详解

转载 作者:qq735679552 更新时间:2022-09-27 22:32:09 25 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章iOS常用的公共方法详解由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

1. 获取磁盘总空间大小 。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//磁盘总空间
+ (cgfloat)diskofallsizembytes{
  cgfloat size = 0.0;
  nserror *error;
  nsdictionary *dic = [[nsfilemanager defaultmanager] attributesoffilesystemforpath:nshomedirectory() error:&error];
  if (error) {
#ifdef debug
  nslog(@ "error: %@" , error.localizeddescription);
#endif
  } else {
  nsnumber *number = [dic objectforkey:nsfilesystemsize];
  size = [number floatvalue]/1024/1024;
  }
  return size;
}

2. 获取磁盘可用空间大小 。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//磁盘可用空间
+ (cgfloat)diskoffreesizembytes{
  cgfloat size = 0.0;
  nserror *error;
  nsdictionary *dic = [[nsfilemanager defaultmanager] attributesoffilesystemforpath:nshomedirectory() error:&error];
  if (error) {
#ifdef debug
  nslog(@ "error: %@" , error.localizeddescription);
#endif
  } else {
  nsnumber *number = [dic objectforkey:nsfilesystemfreesize];
  size = [number floatvalue]/1024/1024;
  }
  return size;
}

3. 获取指定路径下某个文件的大小 。

?
1
2
3
4
5
6
//获取文件大小
+ ( long long )filesizeatpath:(nsstring *)filepath{
  nsfilemanager *filemanager = [nsfilemanager defaultmanager];
  if (![filemanager fileexistsatpath:filepath]) return 0;
  return [[filemanager attributesofitematpath:filepath error:nil] filesize];
}

4. 获取文件夹下所有文件的大小 。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
//获取文件夹下所有文件的大小
+ ( long long )foldersizeatpath:(nsstring *)folderpath{
  nsfilemanager *filemanager = [nsfilemanager defaultmanager];
  if (![filemanager fileexistsatpath:folderpath]) return 0;
  nsenumerator *filesenumerator = [[filemanager subpathsatpath:folderpath] objectenumerator];
  nsstring *filename;
  long long folersize = 0;
  while ((filename = [filesenumerator nextobject]) != nil) {
  nsstring *filepath = [folderpath stringbyappendingpathcomponent:filename];
  folersize += [self filesizeatpath:filepath];
  }
  return folersize;
}

5. 获取字符串(或汉字)首字母 。

?
1
2
3
4
5
6
7
8
//获取字符串(或汉字)首字母
+ (nsstring *)firstcharacterwithstring:(nsstring *)string{
  nsmutablestring *str = [nsmutablestring stringwithstring:string];
  cfstringtransform((cfmutablestringref)str, null, kcfstringtransformmandarinlatin, no);
  cfstringtransform((cfmutablestringref)str, null, kcfstringtransformstripdiacritics, no);
  nsstring *pingyin = [str capitalizedstring];
  return [pingyin substringtoindex:1];
}

6. 将字符串数组按照元素首字母顺序进行排序分组 。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//将字符串数组按照元素首字母顺序进行排序分组
+ (nsdictionary *)dictionaryorderbycharacterwithoriginalarray:(nsarray *)array{
  if (array.count == 0) {
  return nil;
  }
  for (id obj in array) {
  if (![obj iskindofclass:[nsstring class ]]) {
   return nil;
  }
  }
  uilocalizedindexedcollation *indexedcollation = [uilocalizedindexedcollation currentcollation];
  nsmutablearray *objects = [nsmutablearray arraywithcapacity:indexedcollation.sectiontitles.count];
  //创建27个分组数组
  for ( int i = 0; i < indexedcollation.sectiontitles.count; i++) {
  nsmutablearray *obj = [nsmutablearray array];
  [objects addobject:obj];
  }
  nsmutablearray *keys = [nsmutablearray arraywithcapacity:objects.count];
  //按字母顺序进行分组
  nsinteger lastindex = -1;
  for ( int i = 0; i < array.count; i++) {
  nsinteger index = [indexedcollation sectionforobject:array[i] collationstringselector:@selector(uppercasestring)];
  [[objects objectatindex:index] addobject:array[i]];
  lastindex = index;
  }
  //去掉空数组
  for ( int i = 0; i < objects.count; i++) {
  nsmutablearray *obj = objects[i];
  if (obj.count == 0) {
   [objects removeobject:obj];
  }
  }
  //获取索引字母
  for (nsmutablearray *obj in objects) {
  nsstring *str = obj[0];
  nsstring *key = [self firstcharacterwithstring:str];
  [keys addobject:key];
  }
  nsmutabledictionary *dic = [nsmutabledictionary dictionary];
  [dic setobject:objects forkey:keys];
  return dic;
}
//获取字符串(或汉字)首字母
+ (nsstring *)firstcharacterwithstring:(nsstring *)string{
  nsmutablestring *str = [nsmutablestring stringwithstring:string];
  cfstringtransform((cfmutablestringref)str, null, kcfstringtransformmandarinlatin, no);
  cfstringtransform((cfmutablestringref)str, null, kcfstringtransformstripdiacritics, no);
  nsstring *pingyin = [str capitalizedstring];
  return [pingyin substringtoindex:1];
}

使用如下

?
1
2
3
nsarray *arr = @[@ "guangzhou" , @ "shanghai" , @ "北京" , @ "henan" , @ "hainan" ];
nsdictionary *dic = [utilities dictionaryorderbycharacterwithoriginalarray:arr];
nslog(@ "\n\ndic: %@" , dic);

输出结果如下

iOS常用的公共方法详解

输出结果 。

7. 获取当前时间 。

?
1
2
3
4
5
6
7
//获取当前时间
//format: @"yyyy-mm-dd hh:mm:ss"、@"yyyy年mm月dd日 hh时mm分ss秒"
+ (nsstring *)currentdatewithformat:(nsstring *)format{
  nsdateformatter *dateformatter = [[nsdateformatter alloc] init];
  [dateformatter setdateformat:format];
  return [dateformatter stringfromdate:[nsdate date]];
}

8. 计算上次日期距离现在多久, 如 xx 小时前、xx 分钟前等 。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
  * 计算上次日期距离现在多久
  *
  * @param lasttime 上次日期(需要和格式对应)
  * @param format1  上次日期格式
  * @param currenttime 最近日期(需要和格式对应)
  * @param format2  最近日期格式
  *
  * @return xx分钟前、xx小时前、xx天前
  */
+ (nsstring *)timeintervalfromlasttime:(nsstring *)lasttime
       lasttimeformat:(nsstring *)format1
        tocurrenttime:(nsstring *)currenttime
       currenttimeformat:(nsstring *)format2{
  //上次时间
  nsdateformatter *dateformatter1 = [[nsdateformatter alloc]init];
  dateformatter1.dateformat = format1;
  nsdate *lastdate = [dateformatter1 datefromstring:lasttime];
  //当前时间
  nsdateformatter *dateformatter2 = [[nsdateformatter alloc]init];
  dateformatter2.dateformat = format2;
  nsdate *currentdate = [dateformatter2 datefromstring:currenttime];
  return [utilities timeintervalfromlasttime:lastdate tocurrenttime:currentdate];
}
+ (nsstring *)timeintervalfromlasttime:(nsdate *)lasttime tocurrenttime:(nsdate *)currenttime{
  nstimezone *timezone = [nstimezone systemtimezone];
  //上次时间
  nsdate *lastdate = [lasttime datebyaddingtimeinterval:[timezone secondsfromgmtfordate:lasttime]];
  //当前时间
  nsdate *currentdate = [currenttime datebyaddingtimeinterval:[timezone secondsfromgmtfordate:currenttime]];
  //时间间隔
  nsinteger intevaltime = [currentdate timeintervalsincereferencedate] - [lastdate timeintervalsincereferencedate];
  //秒、分、小时、天、月、年
  nsinteger minutes = intevaltime / 60;
  nsinteger hours = intevaltime / 60 / 60;
  nsinteger day = intevaltime / 60 / 60 / 24;
  nsinteger month = intevaltime / 60 / 60 / 24 / 30;
  nsinteger yers = intevaltime / 60 / 60 / 24 / 365;
  if (minutes <= 10) {
   return @ "刚刚" ;
  } else if (minutes < 60){
   return [nsstring stringwithformat: @ "%ld分钟前" ,( long )minutes];
  } else if (hours < 24){
   return [nsstring stringwithformat: @ "%ld小时前" ,( long )hours];
  } else if (day < 30){
   return [nsstring stringwithformat: @ "%ld天前" ,( long )day];
  } else if (month < 12){
   nsdateformatter * df =[[nsdateformatter alloc]init];
   df.dateformat = @ "m月d日" ;
   nsstring * time = [df stringfromdate:lastdate];
   return time ;
  } else if (yers >= 1){
   nsdateformatter * df =[[nsdateformatter alloc]init];
   df.dateformat = @ "yyyy年m月d日" ;
   nsstring * time = [df stringfromdate:lastdate];
   return time ;
  }
  return @ "" ;
}

使用如下

?
1
2
3
4
nslog(@ "\n\nresult: %@" , [utilities timeintervalfromlasttime:@ "2015年12月8日 15:50"
lasttimeformat:@ "yyyy年mm月dd日 hh:mm"
tocurrenttime:@ "2015/12/08 16:12"
currenttimeformat:@ "yyyy/mm/dd hh:mm" ]);

输出结果如下

iOS常用的公共方法详解

输出结果 。

9. 判断手机号码格式是否正确 。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//判断手机号码格式是否正确
+ ( bool )valimobile:(nsstring *)mobile{
  mobile = [mobile stringbyreplacingoccurrencesofstring:@ " " withstring:@ "" ];
  if (mobile.length != 11)
  {
   return no;
  } else {
   /**
    * 移动号段正则表达式
    */
   nsstring *cm_num = @ "^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$" ;
   /**
    * 联通号段正则表达式
    */
   nsstring *cu_num = @ "^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$" ;
   /**
    * 电信号段正则表达式
    */
   nsstring *ct_num = @ "^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$" ;
   nspredicate *pred1 = [nspredicate predicatewithformat:@ "self matches %@" , cm_num];
   bool ismatch1 = [pred1 evaluatewithobject:mobile];
   nspredicate *pred2 = [nspredicate predicatewithformat:@ "self matches %@" , cu_num];
   bool ismatch2 = [pred2 evaluatewithobject:mobile];
   nspredicate *pred3 = [nspredicate predicatewithformat:@ "self matches %@" , ct_num];
   bool ismatch3 = [pred3 evaluatewithobject:mobile];
   if (ismatch1 || ismatch2 || ismatch3) {
    return yes;
   } else {
    return no;
   }
  }
}

10. 判断邮箱格式是否正确 。

?
1
2
3
4
5
6
//利用正则表达式验证
+ ( bool )isavailableemail:(nsstring *)email {
  nsstring *emailregex = @ "[a-z0-9a-z._%+-]+@[a-za-z0-9.-]+\\.[a-za-z]{2,4}" ;
  nspredicate *emailtest = [nspredicate predicatewithformat:@ "self matches %@" , emailregex];
  return [emailtest evaluatewithobject:email];
}

11. 将十六进制颜色转换为 uicolor 对象 。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//将十六进制颜色转换为 uicolor 对象
+ (uicolor *)colorwithhexstring:(nsstring *)color{
  nsstring *cstring = [[color stringbytrimmingcharactersinset:[nscharacterset whitespaceandnewlinecharacterset]] uppercasestring];
  // string should be 6 or 8 characters
  if ([cstring length] < 6) {
   return [uicolor clearcolor];
  }
  // strip "0x" or "#" if it appears
  if ([cstring hasprefix:@ "0x" ])
   cstring = [cstring substringfromindex:2];
  if ([cstring hasprefix:@ "#" ])
   cstring = [cstring substringfromindex:1];
  if ([cstring length] != 6)
   return [uicolor clearcolor];
  // separate into r, g, b substrings
  nsrange range;
  range.location = 0;
  range.length = 2;
  //r
  nsstring *rstring = [cstring substringwithrange:range];
  //g
  range.location = 2;
  nsstring *gstring = [cstring substringwithrange:range];
  //b
  range.location = 4;
  nsstring *bstring = [cstring substringwithrange:range];
  // scan values
  unsigned int r, g, b;
  [[nsscanner scannerwithstring:rstring] scanhexint:&r];
  [[nsscanner scannerwithstring:gstring] scanhexint:&g];
  [[nsscanner scannerwithstring:bstring] scanhexint:&b];
  return [uicolor colorwithred:(( float ) r / 255.0f) green:(( float ) g / 255.0f) blue:(( float ) b / 255.0f) alpha:1.0f];
}

12. 对图片进行滤镜处理 。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#pragma mark - 对图片进行滤镜处理
// 怀旧 --> ciphotoeffectinstant       单色 --> ciphotoeffectmono
// 黑白 --> ciphotoeffectnoir       褪色 --> ciphotoeffectfade
// 色调 --> ciphotoeffecttonal       冲印 --> ciphotoeffectprocess
// 岁月 --> ciphotoeffecttransfer      铬黄 --> ciphotoeffectchrome
// cilineartosrgbtonecurve, cisrgbtonecurvetolinear, cigaussianblur, ciboxblur, cidiscblur, cisepiatone, cidepthoffield
+ (uiimage *)filterwithoriginalimage:(uiimage *)image filtername:(nsstring *)name{
  cicontext *context = [cicontext contextwithoptions:nil];
  ciimage *inputimage = [[ciimage alloc] initwithimage:image];
  cifilter *filter = [cifilter filterwithname:name];
  [filter setvalue:inputimage forkey:kciinputimagekey];
  ciimage *result = [filter valueforkey:kcioutputimagekey];
  cgimageref cgimage = [context createcgimage:result fromrect:[result extent]];
  uiimage *resultimage = [uiimage imagewithcgimage:cgimage];
  cgimagerelease(cgimage);
  return resultimage;
}

13. 对图片进行模糊处理 。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#pragma mark - 对图片进行模糊处理
// cigaussianblur ---> 高斯模糊
// ciboxblur  ---> 均值模糊(available in ios 9.0 and later)
// cidiscblur  ---> 环形卷积模糊(available in ios 9.0 and later)
// cimedianfilter ---> 中值模糊, 用于消除图像噪点, 无需设置radius(available in ios 9.0 and later)
// cimotionblur ---> 运动模糊, 用于模拟相机移动拍摄时的扫尾效果(available in ios 9.0 and later)
+ (uiimage *)blurwithoriginalimage:(uiimage *)image blurname:(nsstring *)name radius:(nsinteger)radius{
  cicontext *context = [cicontext contextwithoptions:nil];
  ciimage *inputimage = [[ciimage alloc] initwithimage:image];
  cifilter *filter;
  if (name.length != 0) {
   filter = [cifilter filterwithname:name];
   [filter setvalue:inputimage forkey:kciinputimagekey];
   if (![name isequaltostring:@ "cimedianfilter" ]) {
    [filter setvalue:@(radius) forkey:@ "inputradius" ];
   }
   ciimage *result = [filter valueforkey:kcioutputimagekey];
   cgimageref cgimage = [context createcgimage:result fromrect:[result extent]];
   uiimage *resultimage = [uiimage imagewithcgimage:cgimage];
   cgimagerelease(cgimage);
   return resultimage;
  } else {
   return nil;
  }
}

14. 调整图片饱和度、亮度、对比度 。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
  * 调整图片饱和度, 亮度, 对比度
  *
  * @param image  目标图片
  * @param saturation 饱和度
  * @param brightness 亮度: -1.0 ~ 1.0
  * @param contrast 对比度
  *
  */
+ (uiimage *)colorcontrolswithoriginalimage:(uiimage *)image
          saturation:(cgfloat)saturation
          brightness:(cgfloat)brightness
          contrast:(cgfloat)contrast{
  cicontext *context = [cicontext contextwithoptions:nil];
  ciimage *inputimage = [[ciimage alloc] initwithimage:image];
  cifilter *filter = [cifilter filterwithname:@ "cicolorcontrols" ];
  [filter setvalue:inputimage forkey:kciinputimagekey];
  [filter setvalue:@(saturation) forkey:@ "inputsaturation" ];
  [filter setvalue:@(brightness) forkey:@ "inputbrightness" ];
  [filter setvalue:@(contrast) forkey:@ "inputcontrast" ];
  ciimage *result = [filter valueforkey:kcioutputimagekey];
  cgimageref cgimage = [context createcgimage:result fromrect:[result extent]];
  uiimage *resultimage = [uiimage imagewithcgimage:cgimage];
  cgimagerelease(cgimage);
  return resultimage;
}

15. 创建一张实时模糊效果 view (毛玻璃效果) 。

?
1
2
3
4
5
6
7
//avilable in ios 8.0 and later
+ (uivisualeffectview *)effectviewwithframe:(cgrect)frame{
  uiblureffect *effect = [uiblureffect effectwithstyle:uiblureffectstylelight];
  uivisualeffectview *effectview = [[uivisualeffectview alloc] initwitheffect:effect];
  effectview.frame = frame;
  return effectview;
}

16. 全屏截图 。

?
1
2
3
4
5
6
7
8
9
//全屏截图
+ (uiimage *)shotscreen{
  uiwindow *window = [uiapplication sharedapplication].keywindow;
  uigraphicsbeginimagecontext(window.bounds.size);
  [window.layer renderincontext:uigraphicsgetcurrentcontext()];
  uiimage *image = uigraphicsgetimagefromcurrentimagecontext();
  uigraphicsendimagecontext();
  return image;
}

17. 截取一张 view 生成图片 。

?
1
2
3
4
5
6
7
8
//截取view生成一张图片
+ (uiimage *)shotwithview:(uiview *)view{
  uigraphicsbeginimagecontext(view.bounds.size);
  [view.layer renderincontext:uigraphicsgetcurrentcontext()];
  uiimage *image = uigraphicsgetimagefromcurrentimagecontext();
  uigraphicsendimagecontext();
  return image;
}

18. 截取view中某个区域生成一张图片 。

//截取view中某个区域生成一张图片 。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
+ (uiimage *)shotwithview:(uiview *)view scope:(cgrect)scope{
  cgimageref imageref = cgimagecreatewithimageinrect([self shotwithview:view].cgimage, scope);
  uigraphicsbeginimagecontext(scope.size);
  cgcontextref context = uigraphicsgetcurrentcontext();
  cgrect rect = cgrectmake(0, 0, scope.size.width, scope.size.height);
  cgcontexttranslatectm(context, 0, rect.size.height); //下移
  cgcontextscalectm(context, 1.0f, -1.0f); //上翻
  cgcontextdrawimage(context, rect, imageref);
  uiimage *image = uigraphicsgetimagefromcurrentimagecontext();
  uigraphicsendimagecontext();
  cgimagerelease(imageref);
  cgcontextrelease(context);
  return image;
}

19. 压缩图片到指定尺寸大小 。

?
1
2
3
4
5
6
7
8
//压缩图片到指定尺寸大小
+ (uiimage *)compressoriginalimage:(uiimage *)image tosize:(cgsize)size{
  uiimage *resultimage = image;
  uigraphicsbeginimagecontext(size);
  [resultimage drawinrect:cgrectmake(0, 0, size.width, size.height)];
  uigraphicsendimagecontext();
  return resultimage;
}

20. 压缩图片到指定文件大小 。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//压缩图片到指定文件大小
+ (nsdata *)compressoriginalimage:(uiimage *)image tomaxdatasizekbytes:(cgfloat)size{
  nsdata *data = uiimagejpegrepresentation(image, 1.0);
  cgfloat datakbytes = data.length/1000.0;
  cgfloat maxquality = 0.9f;
  cgfloat lastdata = datakbytes;
  while (datakbytes > size && maxquality > 0.01f) {
   maxquality = maxquality - 0.01f;
   data = uiimagejpegrepresentation(image, maxquality);
   datakbytes = data.length/1000.0;
   if (lastdata == datakbytes) {
    break ;
   } else {
    lastdata = datakbytes;
   }
  }
  return data;
}

21. 获取设备 ip 地址 。

需要先引入下头文件

?
1
2
#import <ifaddrs.h>
#import <arpa/inet.h>

代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//获取设备 ip 地址
+ (nsstring *)getipaddress {
  nsstring *address = @ "error" ;
  struct ifaddrs *interfaces = null;
  struct ifaddrs *temp_addr = null;
  int success = 0;
  success = getifaddrs(&interfaces);
  if (success == 0) {
   temp_addr = interfaces;
   while (temp_addr != null) {
    if (temp_addr->ifa_addr->sa_family == af_inet) {
     if ([[nsstring stringwithutf8string:temp_addr->ifa_name] isequaltostring:@ "en0" ]) {
      address = [nsstring stringwithutf8string:inet_ntoa((( struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
     }
    }
    temp_addr = temp_addr->ifa_next;
   }
  }
  freeifaddrs(interfaces);
  return address;
}

22. 判断字符串中是否含有空格 。

?
1
2
3
4
5
6
7
8
+ ( bool )ishavespaceinstring:(nsstring *)string{
  nsrange _range = [string rangeofstring:@ " " ];
  if (_range.location != nsnotfound) {
   return yes;
  } else {
   return no;
  }
}

23. 判断字符串中是否含有某个字符串 。

?
1
2
3
4
5
6
7
8
+ ( bool )ishavestring:(nsstring *)string1 instring:(nsstring *)string2{
  nsrange _range = [string2 rangeofstring:string1];
  if (_range.location != nsnotfound) {
   return yes;
  } else {
   return no;
  }
}

24. 判断字符串中是否含有中文 。

?
1
2
3
4
5
6
7
8
9
+ ( bool )ishavechineseinstring:(nsstring *)string{
  for (nsinteger i = 0; i < [string length]; i++){
   int a = [string characteratindex:i];
   if (a > 0x4e00 && a < 0x9fff) {
    return yes;
   }
  }
  return no;
}

25. 判断字符串是否全部为数字 。

?
1
2
3
4
5
6
7
8
9
10
+ ( bool )isallnum:(nsstring *)string{
  unichar c;
  for ( int i=0; i<string.length; i++) {
   c=[string characteratindex:i];
   if (! isdigit (c)) {
    return no;
   }
  }
  return yes;
}

26. 绘制虚线 。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*
  ** lineframe:  虚线的 frame
  ** length:  虚线中短线的宽度
  ** spacing:  虚线中短线之间的间距
  ** color:   虚线中短线的颜色
*/
+ (uiview *)createdashedlinewithframe:(cgrect)lineframe
        linelength:( int )length
        linespacing:( int )spacing
        linecolor:(uicolor *)color{
  uiview *dashedline = [[uiview alloc] initwithframe:lineframe];
  dashedline.backgroundcolor = [uicolor clearcolor];
  cashapelayer *shapelayer = [cashapelayer layer];
  [shapelayer setbounds:dashedline.bounds];
  [shapelayer setposition:cgpointmake(cgrectgetwidth(dashedline.frame) / 2, cgrectgetheight(dashedline.frame))];
  [shapelayer setfillcolor:[uicolor clearcolor].cgcolor];
  [shapelayer setstrokecolor:color.cgcolor];
  [shapelayer setlinewidth:cgrectgetheight(dashedline.frame)];
  [shapelayer setlinejoin:kcalinejoinround];
  [shapelayer setlinedashpattern:[nsarray arraywithobjects:[nsnumber numberwithint:length], [nsnumber numberwithint:spacing], nil]];
  cgmutablepathref path = cgpathcreatemutable();
  cgpathmovetopoint(path, null, 0, 0);
  cgpathaddlinetopoint(path, null, cgrectgetwidth(dashedline.frame), 0);
  [shapelayer setpath:path];
  cgpathrelease(path);
  [dashedline.layer addsublayer:shapelayer];
  return dashedline;
}

27. 将字典对象转换为 json 字符串 。

?
1
2
3
4
5
6
7
8
9
10
11
+ (nsstring *)jsonprettystringencoded:(nsdictionary *)dictionary{
  if ([nsjsonserialization isvalidjsonobject:dictionary ]) {
   nserror *error;
   nsdata *jsondata = [nsjsonserialization datawithjsonobject:dictionary options:nsjsonwritingprettyprinted error:&error];
   if (!error) {
    nsstring *json = [[nsstring alloc] initwithdata:jsondata encoding:nsutf8stringencoding];
    return json;
   }
  }
  return nil;
}

28.将数组对象转换为 json 字符串 。

?
1
2
3
4
5
6
7
8
9
10
11
+ (nsstring *)jsonprettystringencoded:(nsarray *)array{
  if ([nsjsonserialization isvalidjsonobject:array]) {
   nserror *error;
   nsdata *jsondata = [nsjsonserialization datawithjsonobject:array options:nsjsonwritingprettyprinted error:&error];
   if (!error) {
    nsstring *json = [[nsstring alloc] initwithdata:jsondata encoding:nsutf8stringencoding];
    return json;
   }
  }
  return nil;
}

29. 获取 wifi 信息 。

需要引入头文件

#import <systemconfiguration/captivenetwork.h> 。

代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
//获取 wifi 信息
- (nsdictionary *)fetchssidinfo {
  nsarray *ifs = (__bridge_transfer nsarray *)cncopysupportedinterfaces();
  if (!ifs) {
   return nil;
  }
  nsdictionary *info = nil;
  for (nsstring *ifnam in ifs) {
   info = (__bridge_transfer nsdictionary *)cncopycurrentnetworkinfo((__bridge cfstringref)ifnam);
   if (info && [info count]) { break ; }
  }
  return info;
}

30. 获取广播地址、本机地址、子网掩码、端口信息 。

需要引入头文件

?
1
2
3
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px menlo; color: #ff4647}span.s1 {font-variant-ligatures: no-common-ligatures; color: #eb905a}span.s2 {font-variant-ligatures: no-common-ligatures}
#import <ifaddrs.h>
#import <arpa/inet.h>
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//获取广播地址、本机地址、子网掩码、端口信息
- (nsmutabledictionary *)getlocalinfoforcurrentwifi {
  nsmutabledictionary *dict = [nsmutabledictionary dictionary];
  struct ifaddrs *interfaces = null;
  struct ifaddrs *temp_addr = null;
  int success = 0;
  // retrieve the current interfaces - returns 0 on success
  success = getifaddrs(&interfaces);
  if (success == 0) {
   // loop through linked list of interfaces
   temp_addr = interfaces;
   //*/
   while (temp_addr != null) {
    if (temp_addr->ifa_addr->sa_family == af_inet) {
     // check if interface is en0 which is the wifi connection on the iphone
     if ([[nsstring stringwithutf8string:temp_addr->ifa_name] isequaltostring:@ "en0" ]) {
      //广播地址
      nsstring *broadcast = [nsstring stringwithutf8string:inet_ntoa((( struct sockaddr_in *)temp_addr->ifa_dstaddr)->sin_addr)];
      if (broadcast) {
       [dict setobject:broadcast forkey:@ "broadcast" ];
      }
//     nslog(@"broadcast address--%@",broadcast);
      //本机地址
      nsstring *localip = [nsstring stringwithutf8string:inet_ntoa((( struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
      if (localip) {
       [dict setobject:localip forkey:@ "localip" ];
      }
//     nslog(@"local device ip--%@",localip);
      //子网掩码地址
      nsstring *netmask = [nsstring stringwithutf8string:inet_ntoa((( struct sockaddr_in *)temp_addr->ifa_netmask)->sin_addr)];
      if (netmask) {
       [dict setobject:netmask forkey:@ "netmask" ];
      }
//     nslog(@"netmask--%@",netmask);
      //--en0 端口地址
      nsstring *interface = [nsstring stringwithutf8string:temp_addr->ifa_name];
      if (interface) {
       [dict setobject:interface forkey:@ "interface" ];
      }
//     nslog(@"interface--%@",interface);
      return dict;
     }
    }
    temp_addr = temp_addr->ifa_next;
   }
  }
  // free memory
  freeifaddrs(interfaces);
  return dict;
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持我! 。

原文链接:http://www.jianshu.com/p/997f96d2a0b5 。

最后此篇关于iOS常用的公共方法详解的文章就讲到这里了,如果你想了解更多关于iOS常用的公共方法详解的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com