目前我正在开发一个iOS应用程序,需要我解析JSON数据(我们公司内部的公告)并在分组的tableview中显示,我已经尝试过 - stringByReplacingOccurrencesOfString并尝试在UITextView中显示链接但我不是得到我需要的结果。我想只显示来自href标签的数据,其中包含一些链接,用户可以点击这些链接查看公告。以下是我写的代码。任何人都可以指出我正确的方向吗?
if (indexPath.section == 0) {
UILabel *issueStatus = [[UILabel alloc] initWithFrame:CGRectMake(10, 2, cell.frame.size.width, 15)];
[issueStatus setText:[[tmpArray objectAtIndex:indexPath.row] objectForKey:@"title"]];
issueStatus.textColor = [UIColor blackColor];
[cell.contentView addSubview:issueStatus];
UITextView *issueStatus2 = [[UITextView alloc] initWithFrame:CGRectMake(10, 20, cell.frame.size.width, 60)];
NSString *str1 = [[[[[[[tmpArray objectAtIndex:indexPath.row] objectForKey:@"body"] valueForKey:@"view"] valueForKey:@"value"] stringByReplacingOccurrencesOfString:@"<p>" withString:@""] stringByReplacingOccurrencesOfString:@"<a href=\"" withString:@"" ] stringByReplacingOccurrencesOfString:@"class=external-link rel=nofollow>" withString:@""];
[issueStatus2 setText:str1];
issueStatus2.editable = NO;
issueStatus2.scrollEnabled = NO;
issueStatus2.dataDetectorTypes = UIDataDetectorTypeLink;
[cell.contentView addSubview:issueStatus2];
及以下是我从JSON中获取的键值对的示例JSON数据,任何人都可以帮助我如何只获取href标签中的链接以显示在我的UITextView中吗?
{
id: "14975323",
type: "page",
status: "current",
title: "How to Re-Open a Resolved Ticket",
body: {
view: {
value: "<p><a href="https://drive.google.com/a/domain.com/file/d/0B9TSHFNjUGsjYmV2a3pzcTFOWXM/edit" class="external-link" rel="nofollow">https://drive.google.com/a/domain.com/file/d/0B9TSHFNjUGsjYmV2a3pzcTFOWXM/edit</a></p>",
representation: "view",
_expandable: {
content: "/rest/api/content/14975323"
}
}
_expandable: {
editor: "",
export_view: "",
anonymous_export_view: "",
storage: ""
}
}
答案 0 :(得分:2)
您可以使用正则表达式从JSON获取URL。例如,
NSString *pattern = @"((?:http|https)(?::\\/{2}[\\w]+)(?:[\\/|\\.]?)(?:[^\\s""]*))";
NSRange range = [yourString rangeOfString:pattern options:NSRegularExpressionSearch];
//credits for the simpler solution go to @Zaph
self.textView.text = [yourString substringWithRange:range];
(该模式可能需要一些调整,我目前无法对其进行测试;它还假设只有一个URL是您的JSON)