Search code examples
jsonxcodehrefstrip

Make href hypertext links in JSON strings work in iOS app


I'm using JSON in my app to call elements from a database.
One of these elements is a text block with href links.

The JSON looks like :

"textBlock":"<a href=\"http:\/\/www.website.com\/" target=\"_blank\">Link<\/a>

In my app I call label with :

self.TextLabel.text = self.item[@"textBlock"];
[selfTextLabel sizeToFit];

Result in my app shows :

<a href="http://www.website.com/" target="_blank">Link</a>

Would it be possible to write / strip this link properly ?

I came across this solution to strip the html, which works fine, but my links don't work, I would like to know if I can keep my links working.


Solution

  • OK, so after some more searching and trying, I finally got what I needed.

    I first tried to put my string in UITextView, selectable with links detection. Would have been great if I had written directly my URLs in the text.

    But again, the strings I receive from JSON look like :

    <a href="http://www.website.com/" target="_blank">Link</a>
    

    I looked at Fancy UILabels and NSDataDetector, but it seemed like the labels were working but still showing http:// which looked not good for me.

    So I figured best way was to put this string in a UIWebView, and call it like (I replaced TextLabel in the question with TextView).

    [self.TextView loadHTMLString:self.item[@"textBlock"] baseURL:nil];
    

    I finally had some last issue, as the links were opening in the UIWebView instead of Safari.

    So I added self.TextView.delegate = self; in viewDidLoad.

    And

    -(BOOL) webView:(UIWebView *)TextView shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType {
        if ( inType == UIWebViewNavigationTypeLinkClicked ) {
            [[UIApplication sharedApplication] openURL:[inRequest URL]];
            return NO;
        }
    
        return YES;
    }
    

    .h file must also call UIWebViewDelegate.

    And if you think UIWebView default font is ugly in this case, like I did, you can do :

    NSString *nicerTextBlock = self.item[@"textBlock"];
    [self.textView loadHTMLString:[NSString stringWithFormat:@"<style type='text/css'>body { font-family: Helvetica; font-size: 12 } ></style>%@", nicerTextBlock] baseURL:nil];
    

    Hope this can spare some time for other people.