Utils.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. //
  2. // Utils.m
  3. // iosapp
  4. //
  5. // Created by chenhaoxiang on 14-10-16.
  6. // Copyright (c) 2014年 oschina. All rights reserved.
  7. //
  8. #import "Utils.h"
  9. #import "AppDelegate.h"
  10. #import "UIFont+FontAwesome.h"
  11. #import "NSString+FontAwesome.h"
  12. #import "MBProgressHUD.h"
  13. #import <objc/runtime.h>
  14. #import "SDWebImage/UIImageView+WebCache.h"
  15. #import "UIImageView+WebCache.h"
  16. @implementation Utils
  17. #pragma mark - 处理API返回信息
  18. + (NSAttributedString *)getAppclient:(int)clientType
  19. {
  20. NSMutableAttributedString *attributedClientString;
  21. if (clientType > 1 && clientType <= 6) {
  22. NSArray *clients = @[@"", @"", @"手机", @"Android", @"iPhone", @"Windows Phone", @"微信"];
  23. attributedClientString = [[NSMutableAttributedString alloc] initWithString:[NSString fontAwesomeIconStringForEnum:FAMobile]
  24. attributes:@{
  25. NSFontAttributeName: [UIFont fontAwesomeFontOfSize:13],
  26. }];
  27. [attributedClientString appendAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@" %@", clients[clientType]]]];
  28. } else {
  29. attributedClientString = [[NSMutableAttributedString alloc] initWithString:@""];
  30. }
  31. return attributedClientString;
  32. }
  33. + (NSString *)generateRelativeNewsString:(NSArray *)relativeNews
  34. {
  35. if (relativeNews == nil || [relativeNews count] == 0) {
  36. return @"";
  37. }
  38. NSString *middle = @"";
  39. for (NSArray *news in relativeNews) {
  40. middle = [NSString stringWithFormat:@"%@<a href=%@>%@</a><p/>", middle, news[1], news[0]];
  41. }
  42. return [NSString stringWithFormat:@"相关文章<div style='font-size:14px'><p/>%@</div>", middle];
  43. }
  44. + (NSString *)generateTags:(NSArray *)tags
  45. {
  46. if (tags == nil || tags.count == 0) {
  47. return @"";
  48. } else {
  49. NSString *result = @"";
  50. for (NSString *tag in tags) {
  51. result = [NSString stringWithFormat:@"%@<a style='background-color: #BBD6F3;border-bottom: 1px solid #3E6D8E;border-right: 1px solid #7F9FB6;color: #284A7B;font-size: 12pt;-webkit-text-size-adjust: none;line-height: 2.4;margin: 2px 2px 2px 0;padding: 2px 4px;text-decoration: none;white-space: nowrap;' href='http://www.oschina.net/question/tag/%@' >&nbsp;%@&nbsp;</a>&nbsp;&nbsp;", result, tag, tag];
  52. }
  53. return result;
  54. }
  55. }
  56. #pragma mark - 通用
  57. #pragma mark - emoji Dictionary
  58. + (NSDictionary *)emojiDict
  59. {
  60. static dispatch_once_t once;
  61. static NSDictionary *emojiDict;
  62. dispatch_once(&once, ^ {
  63. NSBundle *bundle = [NSBundle mainBundle];
  64. NSString *path = [bundle pathForResource:@"emoji" ofType:@"plist"];
  65. emojiDict = [[NSDictionary alloc] initWithContentsOfFile:path];
  66. });
  67. return emojiDict;
  68. }
  69. #pragma mark 信息处理
  70. + (NSAttributedString *)emojiStringFromRawString:(NSString *)rawString
  71. {
  72. NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:rawString attributes:nil];
  73. return [Utils emojiStringFromAttrString:attrString];
  74. }
  75. + (NSAttributedString *)emojiStringFromAttrString:(NSAttributedString*)attrString
  76. {
  77. NSMutableAttributedString *emojiString = [[NSMutableAttributedString alloc] initWithAttributedString:attrString];
  78. NSDictionary *emoji = self.emojiDict;
  79. NSString *pattern = @"\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]|:[a-zA-Z0-9\\u4e00-\\u9fa5_]+:";
  80. NSError *error = nil;
  81. NSRegularExpression *re = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
  82. NSArray *resultsArray = [re matchesInString:attrString.string options:0 range:NSMakeRange(0, attrString.string.length)];
  83. NSMutableArray *emojiArray = [NSMutableArray arrayWithCapacity:resultsArray.count];
  84. for (NSTextCheckingResult *match in resultsArray) {
  85. NSRange range = [match range];
  86. NSString *emojiName = [attrString.string substringWithRange:range];
  87. if ([emojiName hasPrefix:@"["] && emoji[emojiName]) {
  88. NSTextAttachment *textAttachment = [NSTextAttachment new];
  89. textAttachment.image = [UIImage imageNamed:emoji[emojiName]];
  90. [textAttachment adjustY:-3];
  91. NSAttributedString *emojiAttributedString = [NSAttributedString attributedStringWithAttachment:textAttachment];
  92. [emojiArray addObject: @{@"image": emojiAttributedString, @"range": [NSValue valueWithRange:range]}];
  93. } else if ([emojiName hasPrefix:@":"]) {
  94. if (emoji[emojiName]) {
  95. [emojiArray addObject:@{@"text": emoji[emojiName], @"range": [NSValue valueWithRange:range]}];
  96. } else {
  97. UIImage *emojiImage = [UIImage imageNamed:[emojiName stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@":"]]];
  98. NSTextAttachment *textAttachment = [NSTextAttachment new];
  99. textAttachment.image = emojiImage;
  100. [textAttachment adjustY:-3];
  101. NSAttributedString *emojiAttributedString = [NSAttributedString attributedStringWithAttachment:textAttachment];
  102. [emojiArray addObject: @{@"image": emojiAttributedString, @"range": [NSValue valueWithRange:range]}];
  103. }
  104. }
  105. }
  106. for (NSInteger i = emojiArray.count -1; i >= 0; i--) {
  107. NSRange range;
  108. [emojiArray[i][@"range"] getValue:&range];
  109. if (emojiArray[i][@"image"]) {
  110. [emojiString replaceCharactersInRange:range withAttributedString:emojiArray[i][@"image"]];
  111. } else {
  112. [emojiString replaceCharactersInRange:range withString:emojiArray[i][@"text"]];
  113. }
  114. }
  115. return emojiString;
  116. }
  117. + (NSString *)convertRichTextToRawText:(UITextView *)textView
  118. {
  119. NSMutableString *rawText = [[NSMutableString alloc] initWithString:textView.text];
  120. [textView.attributedText enumerateAttribute:NSAttachmentAttributeName
  121. inRange:NSMakeRange(0, textView.attributedText.length)
  122. options:NSAttributedStringEnumerationReverse
  123. usingBlock:^(NSTextAttachment *attachment, NSRange range, BOOL *stop) {
  124. if (!attachment) {return;}
  125. NSString *emojiStr = objc_getAssociatedObject(attachment, @"emoji");
  126. [rawText insertString:emojiStr atIndex:range.location];
  127. }];
  128. NSString *pattern = @"[\ue000-\uf8ff]|[\\x{1f300}-\\x{1f7ff}]|\\x{263A}\\x{FE0F}|☺";
  129. NSError *error = nil;
  130. NSRegularExpression *re = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
  131. NSArray *resultsArray = [re matchesInString:textView.text options:0 range:NSMakeRange(0, textView.text.length)];
  132. NSBundle *bundle = [NSBundle mainBundle];
  133. NSString *path = [bundle pathForResource:@"emojiToText" ofType:@"plist"];
  134. NSDictionary *emojiToText = [[NSDictionary alloc] initWithContentsOfFile:path];
  135. for (NSTextCheckingResult *match in [resultsArray reverseObjectEnumerator]) {
  136. NSString *emoji = [textView.text substringWithRange:match.range];
  137. [rawText replaceCharactersInRange:match.range withString:emojiToText[emoji]];
  138. }
  139. return [rawText stringByReplacingOccurrencesOfString:@"\U0000fffc" withString:@""];
  140. }
  141. + (NSData *)compressImage:(UIImage *)image
  142. {
  143. CGSize size = [self scaleSize:image.size];
  144. UIGraphicsBeginImageContext(size);
  145. [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
  146. UIImage * scaledImage = UIGraphicsGetImageFromCurrentImageContext();
  147. UIGraphicsEndImageContext();
  148. NSUInteger maxFileSize = 500 * 1024;
  149. CGFloat compressionRatio = 0.7f;
  150. CGFloat maxCompressionRatio = 0.1f;
  151. NSData *imageData = UIImageJPEGRepresentation(scaledImage, compressionRatio);
  152. while (imageData.length > maxFileSize && compressionRatio > maxCompressionRatio) {
  153. compressionRatio -= 0.1f;
  154. imageData = UIImageJPEGRepresentation(image, compressionRatio);
  155. }
  156. return imageData;
  157. }
  158. + (CGSize)scaleSize:(CGSize)sourceSize
  159. {
  160. float width = sourceSize.width;
  161. float height = sourceSize.height;
  162. if (width >= height) {
  163. return CGSizeMake(800, 800 * height / width);
  164. } else {
  165. return CGSizeMake(800 * width / height, 800);
  166. }
  167. }
  168. + (BOOL)isURL:(NSString *)string
  169. {
  170. NSString *pattern = @"^(http|https)://.*?$(net|com|.com.cn|org|me|)";
  171. NSPredicate *urlPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
  172. return [urlPredicate evaluateWithObject:string];
  173. }
  174. + (BOOL)isNetworkExist
  175. {
  176. return [self networkStatus] > 0;
  177. }
  178. #pragma mark UI处理
  179. + (CGFloat)valueBetweenMin:(CGFloat)min andMax:(CGFloat)max percent:(CGFloat)percent
  180. {
  181. return min + (max - min) * percent;
  182. }
  183. + (MBProgressHUD *)createHUD
  184. {
  185. UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
  186. MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithWindow:window];
  187. HUD.detailsLabelFont = [UIFont boldSystemFontOfSize:16];
  188. [window addSubview:HUD];
  189. [HUD show:YES];
  190. HUD.removeFromSuperViewOnHide = YES;
  191. //[HUD addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:HUD action:@selector(hide:)]];
  192. return HUD;
  193. }
  194. + (UIImage *)createQRCodeFromString:(NSString *)string
  195. {
  196. NSData *stringData = [string dataUsingEncoding:NSUTF8StringEncoding];
  197. CIFilter *QRFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
  198. // Set the message content and error-correction level
  199. [QRFilter setValue:stringData forKey:@"inputMessage"];
  200. [QRFilter setValue:@"M" forKey:@"inputCorrectionLevel"];
  201. CGFloat scale = 5;
  202. CGImageRef cgImage = [[CIContext contextWithOptions:nil] createCGImage:QRFilter.outputImage fromRect:QRFilter.outputImage.extent];
  203. //Scale the image usign CoreGraphics
  204. CGFloat width = QRFilter.outputImage.extent.size.width * scale;
  205. UIGraphicsBeginImageContext(CGSizeMake(width, width));
  206. CGContextRef context = UIGraphicsGetCurrentContext();
  207. CGContextSetInterpolationQuality(context, kCGInterpolationNone);
  208. CGContextDrawImage(context, CGContextGetClipBoundingBox(context), cgImage);
  209. UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  210. //Cleaning up
  211. UIGraphicsEndImageContext();
  212. CGImageRelease(cgImage);
  213. return image;
  214. }
  215. + (NSAttributedString *)attributedCommentCount:(int)commentCount
  216. {
  217. NSString *rawString = [NSString stringWithFormat:@"%@ %d", [NSString fontAwesomeIconStringForEnum:FACommentsO], commentCount];
  218. NSAttributedString *attributedCommentCount = [[NSAttributedString alloc] initWithString:rawString
  219. attributes:@{
  220. NSFontAttributeName: [UIFont fontAwesomeFontOfSize:12],
  221. }];
  222. return attributedCommentCount;
  223. }
  224. @end