How to Fetch Videos From Youtube By Integrating Youtube API in iOS App

0
Shares
How to Fetch Videos From Youtube By Integrating Youtube API in iOS App
3 (60%) 2 votes

It’s no secret that Google offers a vast number of electronic products as well as services to its end users. However, there are people who need a different kind of access to Google’s services. They are the developers indeed. And Google provides great assistance to all those developers to build multi-platform applications to use those services. It provide different APIs such as Youtube API, Facebook API, Instagram API, etc which can be used in various ways to provide different functionalities in mobile applications.

In this iOS app tutorial, we’ll be working with a specific API – Youtube API. now this API is fairly easy to integrate and implement. So let’s get going and by the end of this Youtube API tutorial, you’ll be able to fetch youtube videos directly in your iOS app.

Getting Started

First go to Developer Console and create an app.

Once you open the link, it will open a pop-up message. Click on add your project name and click on ‘Create’.

youtube1

youtube2

Once you create app, you’ll be redirected to ‘Dashboard’.

Now go to the library and click on “Youtube Data API”.

youtube3

Next, from dashboard enable the app to use API.

youtube4

youtube5

Now go to “Credentials” tab and a pop-up will appear and provide you the API key which we will have to use in the app.

youtube6

Once you have to API key, open your XCode.

Create a new project with “Single View Application”.

youtube7

youtube8

After creating a new project, install Pods to call API.

youtube9

Now we will create a single file “SOYoutubeAPI.Swift” in which we’ll define API KEY and call this API from class.

import Alamofire in “SOYoutubeAPI.swift”

let API_KEY = "<API_KEY>"

To Get Top Videos (Top 50 videos by country).

func getTopVideos(nextPageToken : String, showLoader : Bool, completion:(videosArray : Array<Dictionary<NSObject, AnyObject>>, succses : Bool, nextpageToken : String)-> Void){

        

        

        //load Indicator

        if #available(iOS 9.0, *) {

            Alamofire.Manager.sharedInstance.session.getAllTasksWithCompletionHandler { (response) in

                response.forEach { $0.cancel() }

            }

        } else {

            // Fallback on earlier versions

            Alamofire.Manager.sharedInstance.session.getTasksWithCompletionHandler({ (dataTasks, uploadTasks, downloadTasks) in

                dataTasks.forEach { $0.cancel() }

                uploadTasks.forEach { $0.cancel() }

                downloadTasks.forEach { $0.cancel() }

            })

        }

        

        let contryCode = self.getCountryCode()

        var arrVideo: Array<Dictionary<NSObject, AnyObject>> = []

        var strURL = "https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics&chart=mostPopular&maxResults=50®ionCode=\(contryCode)&key=\(API_KEY)"

        

        

        strURL = strURL.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!

        

        Alamofire.request(.GET, NSURL(string: strURL)!, parameters: nil, encoding: .URL, headers: nil).responseJSON(completionHandler: { (responseData) -> Void in

            

            

            let isSuccess = responseData.result.isSuccess//JSON(responseData.result.isSuccess)

            if isSuccess {

                

                let resultsDict = responseData.result.value as! Dictionary<NSObject, AnyObject>

                

                

                let items: Array<Dictionary<NSObject, AnyObject>> = resultsDict["items"] as! Array<Dictionary<NSObject, AnyObject>>

                

                for i in 0..<items.count {

                    

                    let snippetDict = items[i]["snippet"] as! Dictionary<NSObject, AnyObject>

                    if !snippetDict["title"]! .isEqualToString("Private video") && !snippetDict["title"]! .isEqualToString("Deleted video"){

                        let statisticsDict = items[i]["statistics"] as! Dictionary<NSObject, AnyObject>

                        

                        var videoDetailsDict = Dictionary<NSObject, AnyObject>()

                        videoDetailsDict["videoTitle"] = snippetDict["title"]

                        videoDetailsDict["videoSubTitle"] = snippetDict["channelTitle"]

                        videoDetailsDict["channelId"] = snippetDict["channelId"]

                        videoDetailsDict["imageUrl"] = ((snippetDict["thumbnails"] as! Dictionary<NSObject, AnyObject>)["high"] as! Dictionary<NSObject, AnyObject>)["url"]

                        videoDetailsDict["videoId"] = items[i]["id"] as! String//PVideoViewCount

                        videoDetailsDict["viewCount"] = statisticsDict["viewCount"]

                        arrVideo.append(videoDetailsDict)

                    }

                }

                

                dispatch_async(dispatch_get_main_queue(), { () -> Void in

                    completion(videosArray: arrVideo, succses: true,nextpageToken: self.strNextPageToken)

                })

            } else {

                

            }

        })

    }

And to get videos from text search (search screen).

func getVideoWithTextSearch (searchText:String, nextPageToken:String, completion:(videosArray : Array<Dictionary<NSObject, AnyObject>>,succses:Bool,nextpageToken:String)-> Void){

        

        

        if #available(iOS 9.0, *) {

            Alamofire.Manager.sharedInstance.session.getAllTasksWithCompletionHandler { (response) in

                response.forEach { $0.cancel() }

            }

        } else {

            // Fallback on earlier versions

            Alamofire.Manager.sharedInstance.session.getTasksWithCompletionHandler({ (dataTasks, uploadTasks, downloadTasks) in

                dataTasks.forEach { $0.cancel() }

                uploadTasks.forEach { $0.cancel() }

                downloadTasks.forEach { $0.cancel() }

            })

        }

        

        let contryCode = self.getCountryCode()

        var arrVideo: Array<Dictionary<NSObject, AnyObject>> = []

        var arrVideoFinal: Array<Dictionary<NSObject, AnyObject>> = []

        

        var strURL = "https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=20&order=Relevance&q=\(searchText)®ionCode=\(contryCode)&type=video&key=\(API_KEY)"

        

        strURL = strURL.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!

        Alamofire.request(.GET, NSURL(string: strURL)!, parameters: nil, encoding: .URL, headers: nil).responseJSON(completionHandler: { (responseData) -> Void in

            

            let isSuccess = responseData.result.isSuccess

            if isSuccess {

                let resultsDict = responseData.result.value as! Dictionary<NSObject, AnyObject>

                

                let items: Array<Dictionary<NSObject, AnyObject>> = resultsDict["items"] as! Array<Dictionary<NSObject, AnyObject>>

                

                let arrayViewCount = NSMutableArray()

                for i in 0..<items.count {

                    

                    let snippetDict = items[i]["snippet"] as! Dictionary<NSObject, AnyObject>

                    

                    if !snippetDict["title"]! .isEqualToString("Private video") && !snippetDict["title"]! .isEqualToString("Deleted video") && items[i]["id"]!["videoId"]! != nil{

                        var videoDetailsDict = Dictionary<NSObject, AnyObject>()

                        arrayViewCount.addObject(items[i]["id"]!["videoId"]! as! String)

                        

                        videoDetailsDict["videoTitle"] = snippetDict["title"]

                        videoDetailsDict["videoSubTitle"] = snippetDict["channelTitle"]

                        videoDetailsDict["channelId"] = snippetDict["channelId"]

                        videoDetailsDict["imageUrl"] = ((snippetDict["thumbnails"] as! Dictionary<NSObject, AnyObject>)["high"] as! Dictionary<NSObject, AnyObject>)["url"]

                        videoDetailsDict["videoId"] = items[i]["id"]!["videoId"]! as! String

                        arrVideo.append(videoDetailsDict)

                    }

                }

                

                //Get video count

                

                if arrayViewCount.count > 0{

                    let videoUrlString = "https://www.googleapis.com/youtube/v3/videos?part=statistics&id=\(arrayViewCount.componentsJoinedByString(","))&key=\(API_KEY)"

                    

                    

                    Alamofire.request(.GET, NSURL(string: videoUrlString)!, parameters: nil, encoding: .URL, headers: nil).responseJSON(completionHandler: { (responseData) -> Void in

                        

                        let isSuccess = responseData.result.isSuccess//JSON(responseData.result.isSuccess)

                        if isSuccess {

                            let resultsDict = responseData.result.value as! Dictionary<NSObject, AnyObject>

                            let items: Array<Dictionary<NSObject, AnyObject>> = resultsDict["items"] as! Array<Dictionary<NSObject, AnyObject>>

                            

                            for i in 0..<items.count {

                                

                                var videoDetailsDict = arrVideo[i]

                                let statisticsDict = items[i]["statistics"] as! Dictionary<NSObject, AnyObject>

                                videoDetailsDict["viewCount"] = statisticsDict["viewCount"]

                                arrVideoFinal.append(videoDetailsDict)

                            }

                            dispatch_async(dispatch_get_main_queue(), { () -> Void in

                                completion(videosArray: arrVideoFinal, succses: true,nextpageToken: self.strNextPageToken)

                            })

                        }else{

                            dispatch_async(dispatch_get_main_queue(), { () -> Void in

                                completion(videosArray: arrVideoFinal, succses: false,nextpageToken: self.strNextPageToken)

                            })

                        }

                    })

                }else{

                    dispatch_async(dispatch_get_main_queue(), { () -> Void in

                        completion(videosArray: arrVideoFinal, succses: false,nextpageToken: self.strNextPageToken)

                    })

                }

            } else {

                

                dispatch_async(dispatch_get_main_queue(), { () -> Void in

                    completion(videosArray: arrVideoFinal, succses: false,nextpageToken: self.strNextPageToken)

                })

            }

        })

    }

Next, we will create 2 different classes and name them as TopVideosVC.swift and SearchVC.swift

In “TopVideosVC.swift set outlet of TableView from Storyboard and allocate an Array.

@IBOutlet weak var tblTopvideos: UITableView!

    let arrVideos = NSMutableArray()

After this, we will call API from SOYoutubeAPI.Swift by following code.

func getTopVideosFromYoutube(sender:AnyObject) {

        SOYoutubeAPI().getTopVideos("", showLoader : false) { (videosArray, succses, nextpageToken) in

            if succses == true {

                print(videosArray)

                self.arrVideos.addObjectsFromArray(videosArray)

                self.tblTopvideos.reloadData()

            }

        }

    }

Now in SearchVC.swift set outlet of UITableView and search bar and get the array.

@IBOutlet weak var tblSearchVideos: UITableView!

    @IBOutlet weak var searchBarvideo: UISearchBar!

    var arrSearch = NSMutableArray()

Next, we’ll set delegate of “UISearchBar”.

When user enter word UISearchBar Delegate will be called

// MARK: - Searchbar Delegate -

    func searchBarTextDidBeginEditing(searchBar: UISearchBar) {

        tblSearchVideos.reloadData()

    }

    

    func searchBarSearchButtonClicked(searchBar: UISearchBar) {

        tblSearchVideos.reloadData()

        searchBar.resignFirstResponder()

    }

    

    func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {

        if searchBar.text == "" {

            self.arrSearch.removeAllObjects()

            self.tblSearchVideos.reloadData()

            return

        }else if searchText.characters.count > 1 {

            self.arrSearch.removeAllObjects()

            self.searchYouttubeVideoData(searchText)

        }else{

            self.arrSearch.removeAllObjects()

            self.tblSearchVideos.reloadData()

        }

    }

If the input text length is greater than one, then it will call API from “SOYoutubeAPI.swift”

//MARK: Search Videos

    func searchYouttubeVideoData(searchText:String) -> Void {

        SOYoutubeAPI().getVideoWithTextSearch(searchText, nextPageToken: "", completion: { (videosArray, succses, nextpageToken) in

            if(succses == true){

                self.arrSearch.addObjectsFromArray(videosArray)

                if(self.arrSearch.count ==  0){

                    self.tblSearchVideos.hidden = true

                }else{

                    self.tblSearchVideos.hidden = false

                }

            }

            self.tblSearchVideos.reloadData()

        })

        

    }

And Done!

If you’ve followed each step in this tutorial, then you know that working with Youtube API is not difficult. However, if you face any problem implementing it, you can contact our iOS developers for help.

As mentioned in introduction, there are many functionalities and features you can add in your mobile app with different APIs. But since we’re talking about Youtube API, you can offer other actions like upload a video directly from App or modify your playlist, apart from fetching videos from youtube.

And if you want to implement such features, you better take assistance of a technical person who knows how to do it right and how to do it well. If you lack of such resource, you can hire iPhone app developer from us to help you add these features.

Grab a free copy of Youtube API demo from Github.

This page was last edited on November 9th, 2016, at 12:18.
 
0
Shares
 

Want to Integrate Third-Party APIs ? Contact Us Now

Get your free consultation now