BGUtils.m 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  1. //
  2. // BGUtils.m
  3. // BuguLive
  4. //
  5. // Created by xfg on 2017/3/14.
  6. // Copyright © 2017年 xfg. All rights reserved.
  7. //
  8. #import "BGUtils.h"
  9. #import "UIImageView+WebCache.h"
  10. #import <mach/mach.h>
  11. #import <Photos/Photos.h>
  12. @implementation BGUtils
  13. #pragma mark - ----------------------- 图片 -----------------------
  14. #pragma mark 下载图片
  15. + (void)downloadImage:(NSString *)url place:(UIImage *)place imageView:(UIImageView *)imageView
  16. {
  17. [imageView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:place options:SDWebImageLowPriority | SDWebImageRetryFailed];
  18. }
  19. #pragma marks 画虚线
  20. + (UIImageView *)dottedLine:(CGRect)frame
  21. {
  22. UIImageView *imageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, frame.size.height)];
  23. UIGraphicsBeginImageContext(imageView1.frame.size); //开始画线
  24. [imageView1.image drawInRect:CGRectMake(0, 0, imageView1.frame.size.width, imageView1.frame.size.height)];
  25. CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound); //设置线条终点形状
  26. CGFloat lengths[] = {2,2};
  27. CGContextRef line = UIGraphicsGetCurrentContext();
  28. CGContextSetStrokeColorWithColor(line, RGB(200, 200, 200).CGColor);
  29. CGContextSetLineDash(line, 0, lengths, 2); //画虚线
  30. CGContextMoveToPoint(line, 0.0, frame.size.height); //开始画线
  31. CGContextAddLineToPoint(line, frame.size.width, frame.size.height);
  32. CGContextStrokePath(line);
  33. imageView1.image = UIGraphicsGetImageFromCurrentImageContext();
  34. return imageView1;
  35. }
  36. #pragma mark 根据颜色生成图片
  37. + (UIImage*)imageWithColor:(UIColor*)color
  38. {
  39. return [BGUtils imageWithColor:color andSize:CGSizeMake(1.0f, 1.0f)];
  40. }
  41. #pragma mark 根据颜色返回图片
  42. + (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)size
  43. {
  44. CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
  45. UIGraphicsBeginImageContext(rect.size);
  46. CGContextRef context = UIGraphicsGetCurrentContext();
  47. CGContextSetFillColorWithColor(context, [color CGColor]);
  48. CGContextFillRect(context, rect);
  49. UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  50. UIGraphicsEndImageContext();
  51. return image;
  52. }
  53. #pragma mark 通过图片Data数据第一个字节 来获取图片扩展名
  54. + (NSString *)contentTypeForImageData:(NSData *)data
  55. {
  56. uint8_t c;
  57. [data getBytes:&c length:1];
  58. switch (c)
  59. {
  60. case 0xFF:
  61. return @"jpeg";
  62. case 0x89:
  63. return @"png";
  64. case 0x47:
  65. return @"gif";
  66. case 0x49:
  67. case 0x4D:
  68. return @"tiff";
  69. case 0x52:
  70. if ([data length] < 12)
  71. {
  72. return nil;
  73. }
  74. NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
  75. if ([testString hasPrefix:@"RIFF"]
  76. && [testString hasSuffix:@"WEBP"])
  77. {
  78. return @"webp";
  79. }
  80. return nil;
  81. }
  82. return nil;
  83. }
  84. #pragma mark 图片拉伸
  85. + (UIImage *)resizableImage:(NSString *)imageName
  86. {
  87. return [BGUtils resizableImage:imageName edgeInsets:UIEdgeInsetsMake(0.5, 0.5, 0.5, 0.5)];
  88. }
  89. #pragma mark 图片拉伸2
  90. + (UIImage *)resizableImage:(NSString *)imageName edgeInsets:(UIEdgeInsets)edgeInsets
  91. {
  92. UIImage *image = [UIImage imageNamed:imageName];
  93. CGFloat imageW = image.size.width;
  94. CGFloat imageH = image.size.height;
  95. return [image resizableImageWithCapInsets:UIEdgeInsetsMake(imageH * edgeInsets.top, imageW * edgeInsets.left, imageH * edgeInsets.bottom, imageW * edgeInsets.right) resizingMode:UIImageResizingModeStretch];
  96. }
  97. #pragma mark 获得灰度图
  98. + (UIImage*)covertToGrayImageFromImage:(UIImage*)sourceImage
  99. {
  100. int width = sourceImage.size.width;
  101. int height = sourceImage.size.height;
  102. CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
  103. CGContextRef context = CGBitmapContextCreate (nil,width,height,8,0,colorSpace,kCGImageAlphaNone);
  104. CGColorSpaceRelease(colorSpace);
  105. if (context == NULL)
  106. {
  107. return nil;
  108. }
  109. CGContextDrawImage(context,CGRectMake(0, 0, width, height), sourceImage.CGImage);
  110. CGImageRef contextRef = CGBitmapContextCreateImage(context);
  111. UIImage *grayImage = [UIImage imageWithCGImage:contextRef];
  112. CGContextRelease(context);
  113. CGImageRelease(contextRef);
  114. return grayImage;
  115. }
  116. #pragma mark 根据bundle中的文件名读取图片
  117. + (UIImage *)imageWithFileName:(NSString *)name
  118. {
  119. NSString *extension = @"png";
  120. NSArray *components = [name componentsSeparatedByString:@"."];
  121. if ([components count] >= 2)
  122. {
  123. NSUInteger lastIndex = components.count - 1;
  124. extension = [components objectAtIndex:lastIndex];
  125. name = [name substringToIndex:(name.length-(extension.length+1))];
  126. }
  127. // 如果为Retina屏幕且存在对应图片,则返回Retina图片,否则查找普通图片
  128. if ([UIScreen mainScreen].scale == 2.0)
  129. {
  130. name = [name stringByAppendingString:@"@2x"];
  131. NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:extension];
  132. if (path != nil)
  133. {
  134. return [UIImage imageWithContentsOfFile:path];
  135. }
  136. }
  137. if ([UIScreen mainScreen].scale == 3.0)
  138. {
  139. name = [name stringByAppendingString:@"@3x"];
  140. NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:extension];
  141. if (path != nil)
  142. {
  143. return [UIImage imageWithContentsOfFile:path];
  144. }
  145. }
  146. NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:extension];
  147. if (path)
  148. {
  149. return [UIImage imageWithContentsOfFile:path];
  150. }
  151. return nil;
  152. }
  153. #pragma mark - ----------------------- 字符串 -----------------------
  154. #pragma mark 是否空字符串
  155. + (BOOL)isBlankString:(NSString *)string
  156. {
  157. if (string == nil || string == NULL)
  158. {
  159. return YES;
  160. }
  161. if ([string isKindOfClass:[NSNull class]])
  162. {
  163. return YES;
  164. }
  165. if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0)
  166. {
  167. return YES;
  168. }
  169. if ([string isEqualToString:@"(null)"])
  170. {
  171. return YES;
  172. }
  173. return NO;
  174. }
  175. #pragma mark 判断字符串是否由字符串组成
  176. + (BOOL)isAllNum:(NSString *)string
  177. {
  178. unichar c;
  179. for (int i=0; i<string.length; i++)
  180. {
  181. c=[string characterAtIndex:i];
  182. if (!isdigit(c))
  183. {
  184. return NO;
  185. }
  186. }
  187. return YES;
  188. }
  189. #pragma mark 判断字符串是否为整数型
  190. + (BOOL)isPureInt:(NSString *)string
  191. {
  192. NSScanner* scan = [NSScanner scannerWithString:string];
  193. int val;
  194. return [scan scanInt:&val] && [scan isAtEnd];
  195. }
  196. #pragma mark 判断是否为布谷验证字符串
  197. + (BOOL)isFanwePwd:(NSString*)string
  198. {
  199. if([self isPureInt:string])
  200. {
  201. if([string length] > 7)
  202. {
  203. return YES;
  204. }
  205. else
  206. {
  207. return NO;
  208. }
  209. }
  210. else
  211. {
  212. return NO;
  213. }
  214. }
  215. #pragma mark 解决字符串乱码问题
  216. + (NSString*)returnUF8String:(NSString*)str
  217. {
  218. if ([str canBeConvertedToEncoding:NSShiftJISStringEncoding])
  219. {
  220. str = [NSString stringWithCString:[str cStringUsingEncoding:NSShiftJISStringEncoding] encoding:NSUTF8StringEncoding];
  221. }
  222. return str;
  223. }
  224. #pragma mark float保留的位数,并返回string
  225. + (NSString *)floatReservedString:(float)floatNum markStr:(NSString *)markStr
  226. {
  227. int tmpNum = (int)floatNum;
  228. if (floatNum == tmpNum)
  229. {
  230. return [NSString stringWithFormat:@"%@%.f",markStr,floatNum];
  231. }
  232. else
  233. {
  234. return [NSString stringWithFormat:@"%@%.2f",markStr,floatNum];
  235. }
  236. }
  237. #pragma mark float保留的位数,并返回string
  238. + (NSString *)floatReservedString:(float)floatNum markBackStr:(NSString *)markBackStr
  239. {
  240. int tmpNum = (int)floatNum;
  241. if (floatNum == tmpNum)
  242. {
  243. return [NSString stringWithFormat:@"%.f%@",floatNum,markBackStr];
  244. }
  245. else
  246. {
  247. return [NSString stringWithFormat:@"%.2f%@",floatNum,markBackStr];
  248. }
  249. }
  250. #pragma mark 判断传入的字符串是否符合HTTP路径的语法规则,即”HTTPS://” 或 “HTTP://”
  251. + (NSURL *)smartURLForString:(NSString *)str
  252. {
  253. NSURL * result;
  254. NSString * trimmedStr;
  255. NSRange schemeMarkerRange;
  256. NSString * scheme;
  257. assert(str != nil);
  258. result = nil;
  259. trimmedStr = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
  260. if ( (trimmedStr != nil) && (trimmedStr.length != 0) ) {
  261. schemeMarkerRange = [trimmedStr rangeOfString:@"://"];
  262. if (schemeMarkerRange.location == NSNotFound) {
  263. result = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@", trimmedStr]];
  264. } else {
  265. scheme = [trimmedStr substringWithRange:NSMakeRange(0, schemeMarkerRange.location)];
  266. assert(scheme != nil);
  267. if ( ([scheme compare:@"http" options:NSCaseInsensitiveSearch] == NSOrderedSame)
  268. || ([scheme compare:@"https" options:NSCaseInsensitiveSearch] == NSOrderedSame) ) {
  269. result = [NSURL URLWithString:trimmedStr];
  270. } else {
  271. // It looks like this is some unsupported URL scheme.
  272. }
  273. }
  274. }
  275. return result;
  276. }
  277. #pragma mark 判断此路径是否能够请求成功
  278. + (void)validateUrl:(NSURL *)candidate validateResult:(ValidateUrl)validateResult
  279. {
  280. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:candidate];
  281. [request setHTTPMethod:@"HEAD"];
  282. NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  283. NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  284. NSLog(@"error %@",error);
  285. if (error)
  286. {
  287. if (validateResult)
  288. {
  289. validateResult(candidate,YES);
  290. }
  291. }
  292. else
  293. {
  294. if (validateResult)
  295. {
  296. validateResult(candidate,NO);
  297. }
  298. }
  299. }];
  300. [task resume];
  301. }
  302. #pragma mark 移除字符串中的空格和换行
  303. + (NSString *)removeSpaceAndNewline:(NSString *)str
  304. {
  305. NSString *temp = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
  306. temp = [temp stringByReplacingOccurrencesOfString:@"\r" withString:@""];
  307. temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
  308. return temp;
  309. }
  310. #pragma mark - ----------------------- 时间 -----------------------
  311. #pragma mark 返回当前日期字符串
  312. + (NSString *)dateToString:(NSString*)str
  313. {
  314. NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
  315. [dateFormatter setDateStyle:NSDateFormatterFullStyle];
  316. [dateFormatter setDateFormat:str];//
  317. NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
  318. return dateString;
  319. }
  320. #pragma mark 聊天时间转换
  321. + (NSString *)formatTime:(NSDate*)compareDate
  322. {
  323. if( compareDate == nil ) return @"";
  324. NSTimeInterval timeInterval = [compareDate timeIntervalSinceNow];
  325. timeInterval = -timeInterval;
  326. long temp = timeInterval;
  327. NSString *result;
  328. if (timeInterval < 60) {
  329. if( temp == 0 )
  330. result = ASLocalizedString(@"刚刚");
  331. else
  332. result = [NSString stringWithFormat:ASLocalizedString(@"%d秒前"),(int)temp];
  333. }
  334. else if(( timeInterval/60) <60){
  335. result = [NSString stringWithFormat:ASLocalizedString(@"%d分钟前"),(int)temp/60];
  336. }
  337. else if(( temp/86400) <30){
  338. NSDateFormatter *date = [[NSDateFormatter alloc] init];
  339. [date setDateFormat:@"dd"];
  340. NSString *str = [date stringFromDate:[NSDate date]];
  341. int nowday = [str intValue];
  342. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  343. [dateFormatter setDateFormat:@"dd"];
  344. NSString *strDate = [dateFormatter stringFromDate:compareDate];
  345. int day = [strDate intValue];
  346. if (nowday-day==0) {
  347. [dateFormatter setDateFormat:ASLocalizedString(@"今天 HH:mm")];
  348. result = [dateFormatter stringFromDate:compareDate];
  349. }
  350. else if(nowday-day==1)
  351. {
  352. [dateFormatter setDateFormat:ASLocalizedString(@"昨天 HH:mm")];
  353. result = [dateFormatter stringFromDate:compareDate];
  354. }
  355. else if( temp < 8 )
  356. {
  357. if (temp==1) {
  358. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  359. [dateFormatter setDateFormat:ASLocalizedString(@"昨天HH:mm")];
  360. NSString *strDate = [dateFormatter stringFromDate:compareDate];
  361. result = strDate;
  362. }
  363. else if(temp == 2)
  364. {
  365. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  366. [dateFormatter setDateFormat:ASLocalizedString(@"前天HH:mm")];
  367. NSString *strDate = [dateFormatter stringFromDate:compareDate];
  368. result = strDate;
  369. }
  370. }
  371. else
  372. {
  373. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  374. [dateFormatter setDateFormat:@"MM-dd HH:mm"];
  375. NSString *strDate = [dateFormatter stringFromDate:compareDate];
  376. result = strDate;
  377. }
  378. }
  379. else
  380. {//超过一个月的就直接显示时间了
  381. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  382. [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
  383. NSString *strDate = [dateFormatter stringFromDate:compareDate];
  384. result = strDate;
  385. }
  386. return result;
  387. }
  388. //传入秒得时分秒
  389. +(NSString *)getMMSSFromSS:(NSString *)totalTime{
  390. NSInteger seconds = [totalTime integerValue];
  391. //format of hour
  392. NSString *str_hour = [NSString stringWithFormat:@"%02ld",seconds/3600];
  393. //format of minute
  394. NSString *str_minute = [NSString stringWithFormat:@"%02ld",(seconds%3600)/60];
  395. //format of second
  396. NSString *str_second = [NSString stringWithFormat:@"%02ld",seconds%60];
  397. //format of time
  398. NSString *format_time = [NSString stringWithFormat:@"%@:%@:%@",str_hour,str_minute,str_second];
  399. return format_time;
  400. }
  401. #pragma mark - ----------------------- 颜色 -----------------------
  402. #pragma mark 获取随机色
  403. + (UIColor *)getRandomColor
  404. {
  405. return [UIColor colorWithRed:(float)(1+arc4random()%99)/100 green:(float)(1+arc4random()%99)/100 blue:(float)(1+arc4random()%99)/100 alpha:1];
  406. }
  407. #pragma mark 十六进制转换为uicolor
  408. + (UIColor *)colorWithHexString:(NSString *)color
  409. {
  410. NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
  411. // String should be 6 or 8 characters
  412. if ([cString length] < 6)
  413. {
  414. return [UIColor clearColor];
  415. }
  416. // strip 0X if it appears
  417. if ([cString hasPrefix:@"0X"])
  418. cString = [cString substringFromIndex:2];
  419. if ([cString hasPrefix:@"#"])
  420. cString = [cString substringFromIndex:1];
  421. if ([cString length] != 6)
  422. return [UIColor clearColor];
  423. // Separate into r, g, b substrings
  424. NSRange range;
  425. range.location = 0;
  426. range.length = 2;
  427. //r
  428. NSString *rString = [cString substringWithRange:range];
  429. //g
  430. range.location = 2;
  431. NSString *gString = [cString substringWithRange:range];
  432. //b
  433. range.location = 4;
  434. NSString *bString = [cString substringWithRange:range];
  435. // Scan values
  436. unsigned int r, g, b;
  437. [[NSScanner scannerWithString:rString] scanHexInt:&r];
  438. [[NSScanner scannerWithString:gString] scanHexInt:&g];
  439. [[NSScanner scannerWithString:bString] scanHexInt:&b];
  440. return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
  441. }
  442. #pragma mark - ----------------------- 转换 -----------------------
  443. #pragma mark json转NSString
  444. + (NSString*)dataTOjsonString:(id)object
  445. {
  446. NSString *jsonString = nil;
  447. NSError *error;
  448. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
  449. options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
  450. error:&error];
  451. if (! jsonData)
  452. {
  453. NSLog(@"Got an error: %@", error);
  454. }
  455. else
  456. {
  457. jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  458. }
  459. return jsonString;
  460. }
  461. #pragma mark 将NSDictionary或NSArray转化为JSON串
  462. + (NSData *)toJSONData:(id)theData
  463. {
  464. NSError *error = nil;
  465. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData
  466. options:NSJSONWritingPrettyPrinted
  467. error:&error];
  468. if ([jsonData length] > 0 && error == nil)
  469. {
  470. return jsonData;
  471. }
  472. else
  473. {
  474. return nil;
  475. }
  476. }
  477. #pragma mark 将JSON串转化为NSDictionary
  478. + (NSDictionary *)jsonStrToDict:(NSString *)jsonStr
  479. {
  480. if ([BGUtils isBlankString:jsonStr])
  481. {
  482. return nil;
  483. }
  484. NSError *error;
  485. NSData *data=[jsonStr dataUsingEncoding:NSUTF8StringEncoding];
  486. if (data==nil)
  487. {
  488. NSLog(ASLocalizedString(@"=======将JSON串转化为NSDictionary失败"));
  489. }
  490. else
  491. {
  492. NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
  493. return dic;
  494. }
  495. return nil;
  496. }
  497. #pragma mark - ----------------------- 网络 -----------------------
  498. #pragma mark 判断网络是否连接状态
  499. + (BOOL)isNetConnected
  500. {
  501. BOOL netState;
  502. switch ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus)
  503. {
  504. case AFNetworkReachabilityStatusUnknown:
  505. netState = NO;
  506. break;
  507. case AFNetworkReachabilityStatusNotReachable:
  508. netState = NO;
  509. [FanweMessage alert:ASLocalizedString(@"哎呀!网络不大给力!")];
  510. break;
  511. case AFNetworkReachabilityStatusReachableViaWWAN:
  512. {
  513. netState = YES;
  514. break;
  515. }
  516. case AFNetworkReachabilityStatusReachableViaWiFi:
  517. netState = YES;
  518. break;
  519. default:
  520. break;
  521. }
  522. return netState;
  523. }
  524. #pragma mark - ----------------------- 软硬件 -----------------------
  525. #pragma mark 是否打开闪光灯
  526. + (void)turnOnFlash:(BOOL)isOpen
  527. {
  528. AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  529. if ([device hasTorch])
  530. {
  531. if (isOpen)
  532. {
  533. [device lockForConfiguration:nil];
  534. [device setTorchMode: AVCaptureTorchModeOn];
  535. [device unlockForConfiguration];
  536. }
  537. else
  538. {
  539. [device lockForConfiguration:nil];
  540. [device setTorchMode: AVCaptureTorchModeOff];
  541. [device unlockForConfiguration];
  542. }
  543. }
  544. }
  545. #pragma mark 获取app的cpu使用情况
  546. + (float)getAppCpuUsage
  547. {
  548. kern_return_t kr;
  549. task_info_data_t tinfo;
  550. mach_msg_type_number_t task_info_count;
  551. task_info_count = TASK_INFO_MAX;
  552. kr = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)tinfo, &task_info_count);
  553. if (kr != KERN_SUCCESS)
  554. {
  555. return -1;
  556. }
  557. task_basic_info_t basic_info;
  558. thread_array_t thread_list;
  559. mach_msg_type_number_t thread_count;
  560. thread_info_data_t thinfo;
  561. mach_msg_type_number_t thread_info_count;
  562. thread_basic_info_t basic_info_th;
  563. uint32_t stat_thread = 0; // Mach threads
  564. basic_info = (task_basic_info_t)tinfo;
  565. // get threads in the task
  566. kr = task_threads(mach_task_self(), &thread_list, &thread_count);
  567. if (kr != KERN_SUCCESS)
  568. {
  569. return -1;
  570. }
  571. if (thread_count > 0)
  572. stat_thread += thread_count;
  573. long tot_sec = 0;
  574. long tot_usec = 0;
  575. float tot_cpu = 0;
  576. int j;
  577. for (j = 0; j < thread_count; j++)
  578. {
  579. thread_info_count = THREAD_INFO_MAX;
  580. kr = thread_info(thread_list[j], THREAD_BASIC_INFO, (thread_info_t)thinfo, &thread_info_count);
  581. if (kr != KERN_SUCCESS)
  582. {
  583. return -1;
  584. }
  585. basic_info_th = (thread_basic_info_t)thinfo;
  586. if (!(basic_info_th->flags & TH_FLAGS_IDLE))
  587. {
  588. tot_sec = tot_sec + basic_info_th->user_time.seconds + basic_info_th->system_time.seconds;
  589. tot_usec = tot_usec + basic_info_th->system_time.microseconds + basic_info_th->system_time.microseconds;
  590. tot_cpu = tot_cpu + basic_info_th->cpu_usage / (float)TH_USAGE_SCALE * 100.0;
  591. }
  592. } // for each thread
  593. kr = vm_deallocate(mach_task_self(), (vm_offset_t)thread_list, thread_count * sizeof(thread_t));
  594. assert(kr == KERN_SUCCESS);
  595. return tot_cpu;
  596. }
  597. #pragma mark 统一关闭键盘
  598. + (void)closeKeyboard
  599. {
  600. [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
  601. // 或者 [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
  602. }
  603. #pragma mark 获取app缓存大小
  604. + (CGFloat)getCachSize
  605. {
  606. NSUInteger imageCacheSize = [[SDImageCache sharedImageCache] totalDiskSize];
  607. //获取自定义缓存大小
  608. //用枚举器遍历 一个文件夹的内容
  609. //1.获取 文件夹枚举器
  610. NSString *myCachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
  611. NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:myCachePath];
  612. __block NSUInteger count = 0;
  613. //2.遍历
  614. for (NSString *fileName in enumerator)
  615. {
  616. NSString *path = [myCachePath stringByAppendingPathComponent:fileName];
  617. NSDictionary *fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
  618. count += fileDict.fileSize;//自定义所有缓存大小
  619. }
  620. // 得到是字节 转化为M
  621. CGFloat totalSize = ((CGFloat)imageCacheSize+count)/1024/1024;
  622. return totalSize;
  623. }
  624. #pragma mark 清理app缓存
  625. + (void)handleClearView
  626. {
  627. //删除两部分
  628. //1.删除 sd 图片缓存
  629. //先清除内存中的图片缓存
  630. [[SDImageCache sharedImageCache] clearMemory];
  631. //清除磁盘的缓存
  632. [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
  633. }];
  634. //2.删除自己缓存
  635. NSString *myCachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
  636. [[NSFileManager defaultManager] removeItemAtPath:myCachePath error:nil];
  637. }
  638. #pragma mark 几个常用的权限判断
  639. + (void)judgeAuthorization
  640. {
  641. if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied)
  642. {
  643. NSLog(ASLocalizedString(@"没有定位权限"));
  644. }
  645. AVAuthorizationStatus statusVideo = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  646. if (statusVideo == AVAuthorizationStatusDenied)
  647. {
  648. NSLog(ASLocalizedString(@"没有摄像头权限"));
  649. }
  650. //是否有麦克风权限
  651. AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
  652. if (statusAudio == AVAuthorizationStatusDenied)
  653. {
  654. NSLog(ASLocalizedString(@"没有录音权限"));
  655. }
  656. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
  657. if (status == PHAuthorizationStatusDenied)
  658. {
  659. NSLog(ASLocalizedString(@"没有相册权限"));
  660. }
  661. }];
  662. }
  663. #pragma mark - ----------------------- 坐标 -----------------------
  664. #pragma mark 获取view的坐标在整个window上的位置
  665. + (CGPoint)getPointInWindow:(UIView *)view viewPoint:(CGPoint)viewPoint
  666. {
  667. return [view convertPoint:viewPoint toView:[UIApplication sharedApplication].windows.lastObject];
  668. // return [v.superview convertPoint:v.frame.origin toView:[UIApplication sharedApplication].windows.lastObject];
  669. }
  670. #pragma mark - ----------------------- KVC -----------------------
  671. #pragma mark kvc 获取所有变量
  672. + (NSArray *)getAllIvar:(id)object
  673. {
  674. NSMutableArray *array = [NSMutableArray array];
  675. unsigned int count;
  676. Ivar *ivars = class_copyIvarList([object class], &count);
  677. for (int i = 0; i < count; i++)
  678. {
  679. Ivar ivar = ivars[i];
  680. const char *keyChar = ivar_getName(ivar);
  681. NSString *keyStr = [NSString stringWithCString:keyChar encoding:NSUTF8StringEncoding];
  682. @try {
  683. id valueStr = [object valueForKey:keyStr];
  684. NSDictionary *dic = nil;
  685. if (valueStr)
  686. {
  687. dic = @{keyStr : valueStr};
  688. }
  689. else
  690. {
  691. dic = @{keyStr : ASLocalizedString(@"值为nil")};
  692. }
  693. [array addObject:dic];
  694. }
  695. @catch (NSException *exception) {}
  696. }
  697. return [array copy];
  698. }
  699. #pragma mark kvc 获得所有属性
  700. + (NSArray *)getAllProperty:(id)object
  701. {
  702. NSMutableArray *array = [NSMutableArray array];
  703. unsigned int count;
  704. objc_property_t *propertys = class_copyPropertyList([object class], &count);
  705. for (int i = 0; i < count; i++)
  706. {
  707. objc_property_t property = propertys[i];
  708. const char *nameChar = property_getName(property);
  709. NSString *nameStr = [NSString stringWithCString:nameChar encoding:NSUTF8StringEncoding];
  710. [array addObject:nameStr];
  711. }
  712. return [array copy];
  713. }
  714. +(void)viewShadowPathWithView:(UIView *)view Color:(UIColor *)shadowColor shadowOpacity:(CGFloat)shadowOpacity shadowRadius:(CGFloat)shadowRadius shadowPathType:(LeShadowPathType)shadowPathType shadowPathWidth:(CGFloat)shadowPathWidth{
  715. view.layer.masksToBounds = NO;//必须要等于NO否则会把阴影切割隐藏掉
  716. view.layer.shadowColor = shadowColor.CGColor;// 阴影颜色
  717. view.layer.shadowOpacity = shadowOpacity;// 阴影透明度,默认0
  718. view.layer.shadowOffset = CGSizeMake(0, -5);//shadowOffset阴影偏移,默认(0, -3),这个跟shadowRadius配合使用
  719. // view.layer.shadowRadius = shadowRadius;//阴影半径,默认3
  720. CGRect shadowRect = CGRectZero;
  721. CGFloat originX,originY,sizeWith,sizeHeight;
  722. originX = 0;
  723. originY = 0;
  724. sizeWith = view.bounds.size.width;
  725. sizeHeight = view.bounds.size.height;
  726. if (shadowPathType == LeShadowPathTop) {
  727. shadowRect = CGRectMake(originX, originY-shadowPathWidth/2, sizeWith, shadowPathWidth);
  728. }else if (shadowPathType == LeShadowPathBottom){
  729. shadowRect = CGRectMake(originY, sizeHeight-shadowPathWidth/2, sizeWith, shadowPathWidth);
  730. }else if (shadowPathType == LeShadowPathLeft){
  731. shadowRect = CGRectMake(originX-shadowPathWidth/2, originY, shadowPathWidth, sizeHeight);
  732. }else if (shadowPathType == LeShadowPathRight){
  733. shadowRect = CGRectMake(sizeWith-shadowPathWidth/2, originY, shadowPathWidth, sizeHeight);
  734. }else if (shadowPathType == LeShadowPathCommon){
  735. shadowRect = CGRectMake(originX-shadowPathWidth/2, 2, sizeWith+shadowPathWidth, sizeHeight+shadowPathWidth/2);
  736. }else if (shadowPathType == LeShadowPathAround){
  737. shadowRect = CGRectMake(originX-shadowPathWidth/2, originY-shadowPathWidth/2, sizeWith+shadowPathWidth, sizeHeight+shadowPathWidth);
  738. }
  739. UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRect:shadowRect];
  740. view.layer.shadowPath = bezierPath.CGPath;//阴影路径
  741. }
  742. @end