NSString+RQExtension.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. //
  2. // NSString+RQExtension.m
  3. // RQCommon
  4. //
  5. // Created by 张嵘 on 2018/11/21.
  6. // Copyright © 2018 张嵘. All rights reserved.
  7. //
  8. #import "NSString+RQExtension.h"
  9. #include <CommonCrypto/CommonCrypto.h>
  10. #define xmlRetError @"ERROR:not found <ns:return></ns:return>"
  11. @implementation NSString (RQExtension)
  12. #pragma mark - 文本高度计算
  13. - (CGSize)rq_sizeWithFont:(UIFont *)font {
  14. CGSize theSize;
  15. NSDictionary *attributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
  16. theSize = [self sizeWithAttributes:attributes];
  17. // 向上取整
  18. theSize.width = ceil(theSize.width);
  19. theSize.height = ceil(theSize.height);
  20. return theSize;
  21. }
  22. - (CGSize)rq_sizeWithFont:(UIFont *)font limitSize:(CGSize)limitSize {
  23. CGSize theSize;
  24. NSDictionary *attributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
  25. CGRect rect = [self boundingRectWithSize:limitSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attributes context:nil];
  26. theSize.width = ceil(rect.size.width);
  27. theSize.height = ceil(rect.size.height);
  28. return theSize;
  29. }
  30. - (CGSize)rq_sizeWithFont:(UIFont *)font limitWidth:(CGFloat)limitWidth {
  31. return [self rq_sizeWithFont:font limitSize:CGSizeMake(limitWidth, MAXFLOAT)];
  32. }
  33. #pragma mark - 文本内容处理
  34. - (NSString *)rq_removeBothEndsWhitespace {
  35. return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
  36. }
  37. - (NSString *)rq_removeBothEndsWhitespaceAndNewline {
  38. return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
  39. }
  40. - (NSString *)rq_trimWhitespace {
  41. NSMutableString *str = [self mutableCopy];
  42. CFStringTrimWhitespace((__bridge CFMutableStringRef)str);
  43. return str;
  44. }
  45. - (NSString *)rq_URLEncoding {
  46. NSString * result;
  47. if (@available(iOS 9.0, *)) {
  48. NSString *charactersToEscape = @"#[]@!$'()*+,;\"<>%{}|^~`";
  49. NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
  50. result = [[self description] stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
  51. } else {
  52. #pragma clang diagnostic push
  53. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  54. //这里写出现警告的代码就能实现去除警告
  55. result = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault,
  56. (CFStringRef)self,
  57. NULL,
  58. CFSTR("!*'();:@&=+$,/?%#[]"),
  59. kCFStringEncodingUTF8 ));
  60. #pragma clang diagnostic pop
  61. }
  62. return result;
  63. }
  64. - (NSString *)rq_URLDecoding {
  65. NSString * result;
  66. if (@available(iOS 9.0, *)) {
  67. result = [self stringByRemovingPercentEncoding];
  68. } else {
  69. #pragma clang diagnostic push
  70. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  71. //这里写出现警告的代码就能实现去除警告
  72. result = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)self, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
  73. #pragma clang diagnostic pop
  74. }
  75. return result;
  76. }
  77. - (NSString *)rq_trimAllWhitespace {
  78. return [self stringByReplacingOccurrencesOfString:@" " withString:@""];
  79. }
  80. #pragma mark - 文本内容判断
  81. + (BOOL)rq_isContainChinese:(NSString *)string {
  82. for (int i = 0; i < [string length]; i++) {
  83. int a = [string characterAtIndex:i];
  84. if ( a > 0x4e00 && a < 0x9fff) {
  85. return YES;
  86. }
  87. }
  88. return NO;
  89. }
  90. + (BOOL)rq_isPureInt:(NSString *)string {
  91. NSScanner *scan = [NSScanner scannerWithString:string];
  92. int val;
  93. return [scan scanInt:&val] && [scan isAtEnd];
  94. }
  95. + (BOOL)rq_isPureFloat:(NSString *)string {
  96. NSScanner *scan = [NSScanner scannerWithString:string];
  97. float val;
  98. return [scan scanFloat:&val] && [scan isAtEnd];
  99. }
  100. + (BOOL)rq_isValidMobile:(NSString *)string {
  101. NSString *phoneRegex = @"^1[34578]\\d{9}$";
  102. NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
  103. return [phoneTest evaluateWithObject:string];
  104. }
  105. + (BOOL)rq_isPureDigitCharacters:(NSString *)string {
  106. string = [string stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
  107. if (string.length > 0) {
  108. return NO;
  109. }
  110. return YES;
  111. }
  112. + (BOOL)rq_isValidCharacterOrNumber:(NSString *)string {
  113. // 编写正则表达式:只能是数字或英文,或两者都存在
  114. NSString *regex = @"^[a-z0-9A-Z]*$";
  115. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
  116. return [predicate evaluateWithObject:string];
  117. }
  118. + (BOOL)rq_isEmpty:(NSString *)string {
  119. if (!string) {
  120. return true;
  121. }else {
  122. NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
  123. NSString *trimedString = [string stringByTrimmingCharactersInSet:set];
  124. if ([trimedString length] == 0) {
  125. return true;
  126. }else {
  127. return false;
  128. }
  129. }
  130. }
  131. + (BOOL)rq_isValidEmail:(NSString *)string {
  132. NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
  133. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
  134. return [predicate evaluateWithObject:string];
  135. }
  136. + (BOOL)rq_isValidQQ:(NSString *)string {
  137. NSString *regex = @"^[1-9][0-9]{4,9}$";
  138. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
  139. return [predicate evaluateWithObject:string];
  140. }
  141. + (BOOL)rq_isValidURL:(NSString *)url {
  142. if(url.length < 1)
  143. return NO;
  144. if (url.length>4 && [[url substringToIndex:4] isEqualToString:@"www."]) {
  145. url = [NSString stringWithFormat:@"http://%@",url];
  146. } else {
  147. url = url;
  148. }
  149. NSString *urlRegex = @"(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]";
  150. NSPredicate* urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegex];
  151. return [urlTest evaluateWithObject:url];
  152. }
  153. #pragma mark - Other
  154. -(NSString* )getXlmRet
  155. {
  156. NSMutableString* mstr = [NSMutableString stringWithString:self];
  157. NSRange substr = [mstr rangeOfString:@"<ns:return>"];
  158. NSRange substr2 = [mstr rangeOfString:@"</ns:return>"];
  159. if (substr.location == NSNotFound || substr2.location == NSNotFound) {
  160. return xmlRetError;
  161. }
  162. NSString *result = [mstr substringWithRange:NSMakeRange(substr.location + substr.length, substr2.location - substr.location - substr.length)];
  163. return result;
  164. }
  165. -(NSString*)getCode{
  166. if (![self getXlmRet]) {
  167. return nil;
  168. }
  169. NSDictionary* root = [self jsonObject];
  170. return root[@"code"];
  171. }
  172. -(id)jsonObject
  173. {
  174. NSString* ret = [self getXlmRet];
  175. if (!ret)
  176. {
  177. return nil;
  178. }
  179. //options --dansonpro
  180. NSData* jsonData = [ret dataUsingEncoding:NSUTF8StringEncoding];
  181. NSDictionary* json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
  182. return json;
  183. }
  184. - (NSString *)md5Encrypt
  185. {
  186. const char *cStr = [self UTF8String];
  187. unsigned char result[16];
  188. CC_MD5( cStr, (unsigned int)strlen(cStr), result );
  189. NSString* str = [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
  190. result[0], result[1], result[2], result[3],
  191. result[4], result[5], result[6], result[7],
  192. result[8], result[9], result[10], result[11],
  193. result[12], result[13], result[14], result[15]
  194. ];
  195. str = [self toLower:str];
  196. return str;
  197. }
  198. -(NSString *)toLower:(NSString *)str
  199. {
  200. for (NSInteger i=0; i<str.length; i++) {
  201. if ([str characterAtIndex:i]>='A'&[str characterAtIndex:i]<='Z') {
  202. //A对应ASCII码的65 a对应ASCII码的97
  203. //大写换小写 ASCII编码 --Danson
  204. char temp=[str characterAtIndex:i]+32;
  205. NSRange range=NSMakeRange(i, 1);
  206. str=[str stringByReplacingCharactersInRange:range withString:[NSString stringWithFormat:@"%c",temp]];
  207. }
  208. }
  209. return str;
  210. }
  211. -(NSString *)toHighterWithLower:(NSString *)str
  212. {
  213. for (NSInteger i=0; i<str.length; i++) {
  214. if ([str characterAtIndex:i]>='a'&[str characterAtIndex:i]<='z') {
  215. //A对应ASCII码的65 a对应ASCII码的97
  216. //小写换大写 ASCII编码 --Danson
  217. char temp=[str characterAtIndex:i]-32;
  218. NSRange range=NSMakeRange(i, 1);
  219. str=[str stringByReplacingCharactersInRange:range withString:[NSString stringWithFormat:@"%c",temp]];
  220. }
  221. }
  222. return str;
  223. }
  224. -(CGFloat)heightForWid:(CGFloat)wid Font:(CGFloat)fontSize
  225. {
  226. if (self.length < 1) {
  227. return 20.0;
  228. }
  229. return [self boundingRectWithSize:CGSizeMake(wid, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: [UIFont rq_fontForPingFangSC_RegularFontOfSize:fontSize]} context:nil].size.height;
  230. }
  231. -(CGSize)sizeForFont:(CGFloat)fontSize
  232. {
  233. if (self.length < 1) {
  234. return CGSizeMake(20, 20);
  235. }
  236. return [self boundingRectWithSize:CGSizeMake(MAXFLOAT, 20) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:fontSize]} context:nil].size;
  237. }
  238. -(NSString*)base64
  239. {
  240. NSString* path = [[NSBundle mainBundle] pathForResource:self ofType:nil];
  241. UIImage *_originImage = [UIImage imageNamed:path];
  242. NSData *_data = UIImagePNGRepresentation(_originImage);
  243. NSString *_encodedImageStr = [_data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
  244. return _encodedImageStr;
  245. }
  246. /**
  247. Base64字符串转UIImage图片:、
  248. //UIImage图片转成Base64字符串:
  249. UIImage *originImage = [UIImage imageNamed:@"originImage.png"];
  250. NSData *data = UIImageJPEGRepresentation(originImage, 1.0f);
  251. NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
  252. //Base64字符串转UIImage图片:
  253. NSData *decodedImageData = [[NSData alloc]
  254. initWithBase64EncodedString:encodedImageStr options:NSDataBase64DecodingIgnoreUnknownCharacters];
  255. UIImage *decodedImage = [UIImage imageWithData:decodedImageData];
  256. */
  257. /// 传入 秒 得到 xx:xx:xx
  258. /// @param totalTime 秒数
  259. + (NSString *)getMMSSFromSS:(NSString *)totalTime {
  260. NSInteger seconds = [totalTime integerValue];
  261. //format of hour
  262. NSString *str_hour = [NSString stringWithFormat:@"%02ld",seconds/3600];
  263. //format of minute
  264. NSString *str_minute = [NSString stringWithFormat:@"%02ld",(seconds%3600)/60];
  265. //format of second
  266. NSString *str_second = [NSString stringWithFormat:@"%02ld",seconds%60];
  267. //format of time
  268. NSString *format_time = [NSString stringWithFormat:@"%@:%@:%@",str_hour,str_minute,str_second];
  269. return format_time;
  270. }
  271. - (NSString *)getPinYin {
  272. NSMutableString *pinyin = [[NSMutableString alloc] initWithString:self];
  273. CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
  274. CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
  275. return pinyin.copy;
  276. }
  277. @end
  278. @implementation NSDictionary (Log)
  279. - (NSString *)descriptionWithLocale:(id)locale
  280. {
  281. NSMutableString *str = [NSMutableString string];
  282. [str appendString:@"{\n"];
  283. //遍历字典的所有键值对
  284. [self enumerateKeysAndObjectsUsingBlock:^(id key,id obj, BOOL *stop) {
  285. if (!key) {
  286. key = @"";
  287. }
  288. if (!obj) {
  289. obj = @"";
  290. }
  291. [str appendFormat:@"\t%@ = %@,\n", key, obj];
  292. }];
  293. [str appendString:@"}"];
  294. //查出最后一个,的范围
  295. NSRange range = [str rangeOfString:@","options:NSBackwardsSearch];
  296. if (range.length) {
  297. // 删掉最后一个,
  298. [str deleteCharactersInRange:range];
  299. }
  300. return str;
  301. }
  302. @end
  303. @implementation NSArray (Log)
  304. - (NSString *)descriptionWithLocale:(id)locale
  305. {
  306. NSMutableString *str = [NSMutableString string];
  307. [str appendString:@"[\n"];
  308. //遍历数组的所有元素
  309. [self enumerateObjectsUsingBlock:^(id obj,NSUInteger idx, BOOL *stop) {
  310. [str appendFormat:@"%@,\n", obj];
  311. }];
  312. [str appendString:@"]"];
  313. //查出最后一个,的范围
  314. NSRange range = [str rangeOfString:@","options:NSBackwardsSearch];
  315. if (range.length) {
  316. // 删掉最后一个,
  317. [str deleteCharactersInRange:range];
  318. }
  319. return str;
  320. }
  321. @end