Wednesday, September 27, 2017

Swift - Handling web links in dynamic content

In this post, We are dealing with a dynamic content and we need to handle web links 
and the navigation in the content in an iOS app.

Suppose, below is the dynamic content you got from server. Could be with multiple web links in it also.

Please subscribe www.iossolves.blogspot.com


The weblink should be displayed as a link and we should be in a position to handle the tap of that link.
Where to redirect user and all.

The best solution to handle this is to take a UITextView and turn on web link detection.

--------------------------------------------------------------------------------------------------

        self.tv.text = "Please subscribe www.iossolves.blogspot.com. Thank You!"
        self.tv.delegate = self
        self.tv.dataDetectorTypes = [.link]

--------------------------------------------------------------------------------------------------

We can also turn on link detection from Interface builder also.





Simulator


In the delegate methods, we can check the url and play with the navigation.

--------------------------------------------------------------------------------------------------

    @available(iOS 10.0, *)
    func textView(_ textView: UITextView, shouldInteractWith URL: URL
             in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        return true
    }
    
    func textView(_ textView: UITextView, shouldInteractWith URL: URL
                                                          in characterRange: NSRange) -> Bool {
        return true
    }

--------------------------------------------------------------------------------------------------

Suppose If I need to block blog sites, We can do that like shown below.

--------------------------------------------------------------------------------------------------

    func textView(_ textView: UITextView, shouldInteractWith URL: URL
             in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {

        if URL.absoluteString.contains("blogspot") {  //Blocking Blog sites
            print("Restricted Site!")
            return false
        }

        return true
    }

--------------------------------------------------------------------------------------------------


Hope this post is useful. Feel free to comment incase of any queries.


No comments:

Post a Comment