检测JSON中的链接并使其可单击iOS

时间:2014-03-13 23:32:17

标签: ios objective-c json hyperlink

在我的应用中,我正在解析服务器上的JSON文件中的文本。在一些帖子(文本)中有链接。但现在我无法点击链接。它只是一个干净的文字和帖子,出现在我的文本视图中。那么,如何检测此JSON文本中的链接并使其可单击,并在Safari中打开?

这是我解析帖子的代码:

#import "DEMOSecondViewController.h"
#import "DEMONavigationController.h"
#import "PostsObject.h"
#import "RNBlurModalView.h"
#import "AFNetworking.h"
#import "PostsNextView.h"

#import "KIImagePager.h"
#import "TableHeaderView.h"

#import "DEMOMenuViewController.h"
#import "UIViewController+REFrostedViewController.h"

@interface DEMOSecondViewController ()
@end

@implementation DEMOSecondViewController
@synthesize tableView = _tableView, activityIndicatorView = _activityIndicatorView;
@synthesize fontForCellText;
@synthesize btnFaceBook, btnTwitter, btnTwitter2;
@synthesize strURLToLoad;
@synthesize movies;

- (IBAction)showButtonMenu {
    [self.frostedViewController presentMenuViewController];
}

- (void)refresh:(UIRefreshControl *)refreshControl {
    [refreshControl endRefreshing];
}

-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

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

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

    strURLToLoad = [[NSMutableString alloc] init];

    [btnFaceBook setTitle:@"json-1.php/file.json" forState:UIControlStateDisabled];
    [btnTwitter setTitle:@"json-2.php/file.json" forState:UIControlStateDisabled];
    [btnTwitter2 setTitle:@"json-3.php/file.json" 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 grayColor];

    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 {

    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];

        UIImageView *tempImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"celeb_b3.jpg"]];
        [tempImageView setFrame:self.tableView.frame];

        self.tableView.backgroundView = tempImageView;
    }

    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;
}

- (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
{
    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;
}


@end

1 个答案:

答案 0 :(得分:0)

您可以使用NSRegularExpression和类似的模式:

((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)

识别字符串中的网址范围,然后使用NSAttributedString创建包含可点击链接的字符串,以放置在UILabel和其他控件中。