在JSON解析文本中查找URL并创建链接

时间:2014-02-17 20:08:09

标签: ios json uitableview hyperlink

在我的iOS应用程序中,我解析了一些JSON数据并将其显示在自定义表视图中。 JSON数据是一种馈送,在某些帖子中有链接。当帖子出现在表格视图的单元格中时,我希望(如果包含)链接可以在Safari中单击并打开。怎么办呢?

这是我解析数据的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
    [refreshControl setTintColor:[UIColor greenColor]];
    [refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
    [self.tableView addSubview:refreshControl];

    strURLToLoad = [[NSMutableString alloc] init];

    [btnFaceBook setTitle:@"link-1.com/json.php" forState:UIControlStateDisabled];
    [btnTwitter setTitle:@"link-2.com/json.php" forState:UIControlStateDisabled];
    [btnTwitter2 setTitle:@"link-3.com/json.php" forState:UIControlStateDisabled];

    [btnFaceBook setTag:@"facebookButton"];
    [btnTwitter setTag:@"twitterButton"];
    [btnTwitter2 setTag:@"twitter2Button"];

    [btnFaceBook setBackgroundImage:[UIImage imageNamed:@"tab_selected.png"] forState:UIControlStateNormal];
    [btnFaceBook setBackgroundImage:[UIImage imageNamed:@"tab_unselected.png"] forState:UIControlStateSelected];

    [btnTwitter setBackgroundImage:[UIImage imageNamed:@"tab_selected.png"] forState:UIControlStateNormal];
    [btnTwitter setBackgroundImage:[UIImage imageNamed:@"tab_unselected.png"] forState:UIControlStateSelected];

    [btnTwitter2 setBackgroundImage:[UIImage imageNamed:@"tab_selected.png"] forState:UIControlStateNormal];
    [btnTwitter2 setBackgroundImage:[UIImage imageNamed:@"tab_unselected.png"] forState:UIControlStateSelected];



    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"PostsObject" owner:self options:nil];
    PostsObject *cell = [nib objectAtIndex:0];
    fontForCellText = cell.title.font;
    cellTextWidth = cell.title.frame.size.width;
    cellHeightExceptText = cell.frame.size.height - cell.title.frame.size.height;

    [self.navigationController setNavigationBarHidden:YES];

    self.tableView.separatorColor = [UIColor clearColor];

    // Setting Up Activity Indicator View
    self.activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];

    self.activityIndicatorView.color = [UIColor greenColor];


    self.activityIndicatorView.hidesWhenStopped = YES;
    self.activityIndicatorView.center = self.view.center;
    [self.view addSubview:self.activityIndicatorView];
    [self.activityIndicatorView startAnimating];
    self.tableView.separatorColor = [UIColor clearColor];

    // Initializing Data Source
    movies = [[NSMutableArray alloc] init];

    [self btnFromTabBarClicked:btnFaceBook];
}

- (void)loadJSONFromCurrentURL
{
    [self.activityIndicatorView startAnimating];

    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:strURLToLoad]];

    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        [movies setArray:JSON];
        [self.activityIndicatorView stopAnimating];
        [self.tableView reloadData];

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
    }];

    [operation start];
}

- (IBAction)btnFromTabBarClicked:(UIButton *)sender
{
    btnFaceBook.selected = btnTwitter.selected = btnTwitter2.selected = NO;

    sender.selected = YES;

    [strURLToLoad setString:[sender titleForState:UIControlStateDisabled]];

    [self loadJSONFromCurrentURL];
}

// Table View Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return movies.count;

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if(indexPath.row == 0) {
        static NSString *Identifier1 = @"TableHeaderView";


        TableHeaderView *cell = [tableView dequeueReusableCellWithIdentifier:Identifier1];
        if (cell == nil) {
            NSArray *nib= [[NSBundle mainBundle] loadNibNamed:@"TableHeaderView" owner:self options:nil];
            cell = (TableHeaderView *)[nib objectAtIndex:0];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;

            cell.backgroundColor = [UIColor clearColor];
            return cell;
        }

    } else {
        static NSString *Identifier2 = @"PostsObject";

        PostsObject *cell = [tableView dequeueReusableCellWithIdentifier:Identifier2];
        if (cell == nil) {
            NSArray *nib= [[NSBundle mainBundle] loadNibNamed:@"PostsObject" owner:self options:nil];
            cell = (PostsObject *)[nib objectAtIndex:0];
            cell.backgroundColor = [UIColor clearColor];
        }

        NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];
        NSString *strText = [movie objectForKey:[self getTextKey]];

        CGRect rect = cell.title.frame;
        rect.size.height = [self getHeightForText:strText];
        cell.title.frame = rect;
        cell.title.text = strText;
        cell.arrow.center = CGPointMake(cell.arrow.frame.origin.x, rect.origin.y + rect.size.height/2);
        cell.published.text = [movie objectForKey:[self getPostedTime]];
        cell.twitterName.text = [movie objectForKey:[self getTwitterName]];

        return cell;

    }
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //get the data you want to pass
    NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];

    // Allocate second view you want to open
    PostsNextView *newView = [[PostsNextView alloc] init];
    // pass the data
    newView.theMovie = movie;

    // present view
    [self.navigationController pushViewController:newView animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0) {
        return 202;

    } else {
        NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];
        NSString *strText = [movie objectForKey:[self getTextKey]];

        CGFloat cellHeight = cellHeightExceptText + [self getHeightForText:strText];
        return cellHeight;
    }

}

- (NSString *)getTextKey
{
    return btnTwitter.selected?@"message":@"message";
}

- (NSString *)getPostedTime
{
    return btnTwitter.selected?@"posted":@"published";
}

- (NSString *)getTwitterName
{
    return btnTwitter2.selected?@"user":@"celebname";
}

- (CGFloat)getHeightForText:(NSString *)strText
{
    CGSize constraintSize = CGSizeMake(cellTextWidth, MAXFLOAT);
    CGSize labelSize = [strText sizeWithFont:fontForCellText constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
    NSLog(@"labelSize.height = %f",labelSize.height);
    return labelSize.height;
}

1 个答案:

答案 0 :(得分:0)

在我的iOS应用程序中,我解析了一些JSON数据并将其显示在自定义表视图中。 JSON数据是一种馈送,在某些帖子中有链接。当帖子出现在表格视图的单元格中时,我希望(如果包含)链接可以在Safari中单击并打开。怎么办呢?

我假设您可以测试帖子是否包含链接,因此在cellForRowAtIndexPath:

if (postContainsURL) {
        UIButton *linkButton = [[UIButton alloc] initWithFrame:CGRectMake(x, y, width, height)];
        [linkButton setTitle:postURL forState:UIControlStateNormal];
        [linkButton addTarget:self action:@selector(openLink:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:linkButton];
}

然后,创建此方法:

-(void)openLink:(UIButton*)sender {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:sender.titleLabel.text]];
}
相关问题