本文为CocoaChina网友1026238004投稿
今天改了下之前做的功能,需要拿到试题标题里面的公式图片,这个图片比较特别,因为他在标签中经过了base64。其他的图片都是用的正则在html中匹配拿到图片地址。当时蛋疼坏了... 以下是匹配的代码
- (NSString *)getImagePathInHTML:(NSString *)html withPreferFileName:(NSString *)fileName { NSError *error = nil; NSRegularExpression *expression = [[NSRegularExpression alloc] initWithPattern:@"(]*?>)" options:NSRegularExpressionCaseInsensitive error:&error]; NSArray *array = [expression matchesInString:html options:0 range:NSMakeRange(0, html.length)]; __block NSString *result = nil; [array enumerateObjectsUsingBlock:^(NSTextCheckingResult *obj, NSUInteger idx, BOOL * _Nonnull stop) { NSString *content = [html substringWithRange:obj.range]; NSRange range = [content rangeOfString:fileName]; if (range.location < html.length) { result = content; *stop = YES; } }]; NSRegularExpression *pathExpression = [NSRegularExpression regularExpressionWithPattern:@"(src/s*=/s*"?(.*?)("|>|/s+))" options:NSRegularExpressionCaseInsensitive error:0]; NSArray *pathArray = nil; if (result) { pathArray = [pathExpression matchesInString:result options:0 range:NSMakeRange(0, result.length)]; } if (pathArray.count > 0) { NSTextCheckingResult *checking = pathArray[0]; result = [result substringWithRange:checking.range]; NSRegularExpression *httpExpression = [NSRegularExpression regularExpressionWithPattern:@"((http|file).*)" options:0 error:0]; NSArray *httpChecking = [httpExpression matchesInString:result options:0 range:NSMakeRange(0, result.length)]; if (httpChecking.count > 0) { checking = httpChecking[0]; result = [result substringWithRange:checking.range]; result = [result stringByReplacingOccurrencesOfString:@""" withString:@""]; return result; } } return nil; }
这一次用这个方法可就麻烦了, 之前我也试过看看textView的代理方法里面能不能拿到点击的附件。当时我没有找到,只是找到了文件的名称,所以我就用了上面的方法去匹配。今天我终于找到了返回的data。可以直接转换成图片。代码如下:
- (BOOL)textView:(UITextView *)textView shouldInteractWithTextAttachment:(NSTextAttachment *)textAttachment inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction NS_AVAILABLE_IOS(10_0) { //NSFileWrapper UIImage *image = [UIImage imageWithData:textAttachment.fileWrapper.regularFileContents]; if (image && image.classForCoder == [UIImage class]) { if ([self.delegate respondsToSelector:@selector(topicTabViewCell:selectImage:)]) { [self.delegate topicTabViewCell:self selectImage:image]; } } // NSString *preferFileName = textAttachment.fileWrapper.preferredFilename; // if(preferFileName.length > 0) { // NSString *imagePath = [self getImagePathInHTML:self.html withPreferFileName:preferFileName]; // if (imagePath.length > 0 && [self.delegate respondsToSelector:@selector(topicTabViewCell:selectImage:)]) { // [self.delegate topicTabViewCell:self selectImage:imagePath]; // } // } return YES; }
这是我第一次发稿,写的不好,望多提意见,在此谢过!