Việt Dũng Lê Việt Dũng Lê - 1 year ago 56
Swift Question

How to make a like button for UIWebView?

I'm building a reader-anime app in iOS using swift.

I use UIWebView to display the URL that linked to the anime which people want to read.
I have a FavoriteView (Using TableView)that display the anime that people favorite in TableViewCell.
When people is reading in UIWebView, I want to make a "Like Button" on the navigation bar.

In which, people can press into that "Like Button" and I want to do something to save that click event (or the URL that is being displayed in the WebView, I'm not sure)to store it like an object ( can I do that ? :( ), then I want to pass it in to FavoriteView to display it in the Cell of FavoriteView.

Someone suggests me store that click event ( like an object ) by coredata but I can not imagine what it is.

Answer Source

So let's sum up.

You have a UIWebView embedded in a UINavigationController. What you want to do, is to add a button in the navigation bar, so a user can store the URLs of some websites he/she wants to keep a track of. If a user presses this button, then the URL of the current website is stored within you app and is displayed on a UITableView that you call FavoriteView.

I'll suppose that your FavoriteView and your web view are managed by the same controller If it's not the case, then change the code accordingly to your structure.

If you only need to store URLs, then you can use NSUserDefaults which is much easier to manipulate than Core Data ( as you seem to begin with iOS development, it might be better to start this way ).

Your controller should look like that :

class ViewController: UITableViewDelegate, UITableViewDataSource
   let favoriteView = UITableView()
   let urlArray = Array<NSURL>()
   let webView = UIWebView()

   override func viewDidLoad() {

    // Initialise your views

   // Etc... ( rest of your code )

You must add the following code to your ViewController ( unless the structure of your code is different, then, you should adapt the answer to your current configuration ).

So first, add a button to your UINavigationBar like that :

let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(addButtonTapped))
self.navigationItem.rightBarButtonItem = addButton

Then, you can implement the addButtonTapped method that will be called when your button is tapped :

func addButtonTapped()
    // We first check that the webView actually has a URL, otherwise we return
    guard let url = self.webView.request?.URL
        else {return}

    // Then we store this URL is NSUserDefaults
    // As we will have other URLs to store, it's interesting to store an array of URLs in NSUserDefaults
    let defaults = NSUserDefaults.standardUserDefaults()

    // We first check if the array already exists in NSUserDefaults
    // If it is the case, we use the existing one, if not, we use a new one
    if let existingUrlArray = defaults.objectForKey("keyUrlArray") as? Array<NSURL>
        self.urlArray = existingUrlArray

    defaults.setObject(self.urlArray, forKey: "keyUrlArray")

Finally, you can display the stored URLs in your FavoriteView which is a UITableView. The controller that manages your FavoriteView has to implemented the UITableViewDelegate methods, this way :

// Call this method in viewDidLoad() so your UITableView is initialised
func initialiseFavoriteView()
    self.favoriteView.delegate = self
    self.favoriteView.dataSource = self
    self.favoriteView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cellIdentifier")


// This method fetches the favorites url from NSUserDefaults and store them into self.urlArray which contains the data of your UITableView
func loadFavoritesAndUpdateTableView()
    if let urlArrayCheck = NSUserDefaults.standardUserDefaults().objectForKey("keyUrlArray") as? Array<NSURL>
        self.urlArray = urlArrayCheck


// MARK: UITableViewDelegate methods
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    let cell = tableView.dequeueReusableCellWithIdentifier("cellIdentifier", forIndexPath: indexPath)

    let url = self.urlArray[indexPath.row]
    cell.textLabel?.text = url.absoluteString

    return cell
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return self.urlArray.count

And finally, you want to load the selected URL when you select a cell of your favorite view, so implement this UITableViewDelegate's method :

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    let url = self.urlArray[indexPath.row]
    let request = NSURLRequest(URL: url)

I repeat it one again : you have to adapt that to your code, I guess your UIWebView and your UITableView are not managed by the same controller for instance.