Advertisement
Guest User

Untitled

a guest
Jan 20th, 2020
584
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 13.29 KB | None | 0 0
  1. import UIKit
  2. import Firebase
  3. import FirebaseDatabase
  4. import Alamofire
  5. import os.log
  6.  
  7. class FavoritesViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate{
  8.  
  9.     @IBOutlet weak var favouriteArtistsCollectionView: UICollectionView!
  10.     @IBOutlet weak var favouriteAlbumsCollectionView: UICollectionView!
  11.     @IBOutlet weak var favouriteTracksCollectionView: UICollectionView!
  12.    
  13.     var artistURL = String()
  14.     var albumURL = String()
  15.     var trackURL = String()
  16.    
  17.     var artistName : String!
  18.     var albumName : String!
  19.     var albumID : Int!
  20.    
  21.     var favouriteArtists = [Artist]()
  22.     var favouriteAlbums = [Album]()
  23.     var favouriteTracks = [Track]()
  24.    
  25.     var artistIndex = Int()
  26.     var albumIndex = Int()
  27.     var trackIndex = Int()
  28.    
  29.     typealias JSONStandard = [String : AnyObject]
  30.     var ref: DatabaseReference!
  31.  
  32.     let db = Firestore.firestore()
  33.  
  34.    
  35.         override func viewDidLoad() {
  36.             super.viewDidLoad()
  37.        
  38.             favouriteArtistsCollectionView.delegate = self
  39.             favouriteArtistsCollectionView.dataSource = self
  40.            
  41.             favouriteAlbumsCollectionView.delegate = self
  42.             favouriteAlbumsCollectionView.dataSource = self
  43.            
  44.             favouriteTracksCollectionView.delegate = self
  45.             favouriteTracksCollectionView.dataSource = self
  46.            
  47.             ref = Database.database().reference()
  48.            
  49.             let user = Auth.auth().currentUser
  50.  
  51.             let docRef = db.collection("users").document(user!.uid)
  52.            
  53.             docRef.getDocument { (document, error) in
  54.                  if let document = document, document.exists {
  55.                     let albums : [Any]
  56.                     let tracks : [Any]
  57.                     let docData = document.data()
  58.                     let artists = docData!["favouriteArtists"] as! [Any]
  59.                     if  (docData!["favouriteAlbums"] != nil){
  60.                         albums = (docData!["favouriteAlbums"] as? [Any])!
  61.                         print("albums")
  62.                     } else {
  63.                         albums = []
  64.                     }
  65.                     if  (docData!["favouriteAlbums"] != nil){
  66.                         tracks = docData!["favouriteTracks"] as! [Any]
  67.                         print("albums")
  68.                     } else {
  69.                         tracks = []
  70.                     }
  71.                     self.callDeezerAPI(artists: artists, albums: albums, tracks: tracks)
  72.                  } else {
  73.                      print("Document does not exist")
  74.                   }
  75.             }
  76.         }
  77.        
  78.         //Number of views
  79.         func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  80.             if collectionView == self.favouriteArtistsCollectionView {
  81.                 if (favouriteArtists.count == 0) {
  82.                     collectionView.setEmptyMessage("You still don't have favourite artists, search for one to add it to your list")
  83.                 } else {
  84.                     collectionView.restore()
  85.                 }
  86.               return favouriteArtists.count
  87.             }
  88.             if collectionView == self.favouriteAlbumsCollectionView {
  89.                 if (favouriteAlbums.count == 0) {
  90.                     collectionView.setEmptyMessage("You still don't have favourite albums, search for one to add it to your list")
  91.                 } else {
  92.                     collectionView.restore()
  93.                 }
  94.                 return favouriteAlbums.count
  95.             }
  96.             else {
  97.                 if (favouriteTracks.count == 0) {
  98.                     collectionView.setEmptyMessage("You still don't have favourite tracks, search for one to add it to your list")
  99.                 } else {
  100.                     collectionView.restore()
  101.                 }
  102.                 return favouriteTracks.count
  103.             }
  104.           }
  105.          
  106.         //Populate view
  107.           func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  108.            
  109.             if collectionView == self.favouriteArtistsCollectionView {
  110.                 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "artistsCell", for: indexPath) as! FavouritesCollectionViewCell
  111.                 cell.favouritesImageView.layer.cornerRadius = 12
  112.                 cell.favouritesImageView.image = self.favouriteArtists[indexPath.row].image
  113.                 cell.favouritesLabel.text = self.favouriteArtists[indexPath.row].name
  114.                 return cell
  115.             }
  116.             if collectionView == self.favouriteAlbumsCollectionView {
  117.                 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "albumsCell", for: indexPath) as! FavouritesCollectionViewCell
  118.                 cell.favouritesImageView.layer.cornerRadius = 12
  119.                 cell.favouritesImageView.image = self.favouriteAlbums[indexPath.row].cover
  120.                 cell.favouritesLabel.text = self.favouriteAlbums[indexPath.row].name
  121.                 return cell
  122.             }
  123.             else {
  124.                 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "tracksCell", for: indexPath) as! FavouritesCollectionViewCell
  125.                 cell.favouritesImageView.layer.cornerRadius = 12
  126.                 cell.favouritesImageView.image = self.favouriteTracks[indexPath.row].image
  127.                 cell.favouritesLabel.text = self.favouriteTracks[indexPath.row].title
  128.                 return cell
  129.             }
  130.            
  131.           }
  132.  
  133.        
  134.         func callDeezerAPI(artists: [Any], albums: [Any], tracks: [Any]) {
  135.             for i in artists {
  136.                 artistURL = "https://api.deezer.com/artist/\(i)"
  137.                 AF.request(artistURL).responseJSON(completionHandler: {
  138.                     response in
  139.                     self.parseDataArtist(JSONData: response.data!)
  140.                 })
  141.             }
  142.            for i in albums {
  143.                albumURL = "https://api.deezer.com/album/\(i)"
  144.                AF.request(albumURL).responseJSON(completionHandler: {
  145.                    response in
  146.                    self.parseDataAlbum(JSONData: response.data!)
  147.                })
  148.            }
  149.            for i in tracks {
  150.                trackURL = "https://api.deezer.com/track/\(i)"
  151.                AF.request(trackURL).responseJSON(completionHandler: {
  152.                    response in
  153.                    self.parseDataTrack(JSONData: response.data!)
  154.                })
  155.            }
  156.                
  157.            }
  158.            
  159.            func parseDataArtist(JSONData : Data) {
  160.                do {
  161.                     let readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONStandard
  162.                     let idFromAPI = readableJSON["id"] as? Int
  163.                     let artistName = readableJSON["name"] as? String
  164.                     let mainImageURL =  URL(string: readableJSON["picture_xl"] as! String)
  165.                     let mainImageData = NSData(contentsOf: mainImageURL!)
  166.                     let mainImage = UIImage(data: mainImageData! as Data)
  167.                          
  168.                     addArtist((Artist.init(idFromAPI: idFromAPI!, name: artistName!, image: mainImage!))!)
  169.                     self.favouriteArtistsCollectionView.reloadInputViews()
  170.                     self.favouriteArtistsCollectionView.reloadData()
  171.                    
  172.                }
  173.                catch{
  174.                    print(error)
  175.                }
  176.            }
  177.        
  178.         func parseDataAlbum(JSONData : Data) {
  179.             var artistName : String?
  180.  
  181.             do {
  182.                  let readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONStandard
  183.                  let idFromAPI = readableJSON["id"] as? Int
  184.                  let albumTitle = readableJSON["title"] as? String
  185.                  let mainImageURL =  URL(string: readableJSON["cover_xl"] as! String)
  186.                  let mainImageData = NSData(contentsOf: mainImageURL!)
  187.                  let mainImage = UIImage(data: mainImageData! as Data)
  188.                
  189.                 if let artist = readableJSON["artist"] as? JSONStandard {
  190.                     artistName =  artist["name"] as? String
  191.                 }
  192.                      let artista = (Artist.init(idFromAPI: idFromAPI!, name: artistName!, image: mainImage!))!
  193.                
  194.                  addAlbum((Album.init(idFromAPI: idFromAPI!, name: albumTitle!, cover: mainImage!, artist: artista))!)
  195.                  self.favouriteAlbumsCollectionView.reloadInputViews()
  196.                  self.favouriteAlbumsCollectionView.reloadData()
  197.                
  198.             }
  199.             catch{
  200.                 print(error)
  201.             }
  202.         }
  203.        
  204.         func parseDataTrack(JSONData : Data) {
  205.             var mainImageArtist : UIImage?
  206.  
  207.             do {
  208.                  let readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONStandard
  209.                  let idFromAPI = readableJSON["id"] as! Int
  210.                  let trackName = readableJSON["title"] as! String
  211.                 let duration = readableJSON["duration"] as! Int
  212.                 if let artist = readableJSON["artist"] as? JSONStandard {
  213.                     artistName = artist["name"] as? String
  214.                     let mainImageURLArtist =  URL(string: artist["picture"] as! String)
  215.                     let mainImageDataArtist = NSData(contentsOf: mainImageURLArtist!)
  216.                     mainImageArtist = UIImage(data: mainImageDataArtist! as Data)!
  217.                 }
  218.                
  219.                 let artistObject = Artist(idFromAPI: idFromAPI, name: artistName, image: mainImageArtist!)
  220.                
  221.                
  222.                    
  223.                 if let album = readableJSON["album"] as? JSONStandard{
  224.                 let mainImageURL =  URL(string: album["cover_big"] as! String)
  225.                 let mainImageData = NSData(contentsOf: mainImageURL!)
  226.                 let cover = UIImage(data: mainImageData! as Data)!
  227.                
  228.                 albumName = album["title"] as? String
  229.                 albumID = album["id"] as? Int
  230.                
  231.                 let album = Album.init(idFromAPI: albumID, name: albumName, cover: cover, artist: artistObject)
  232.                
  233.                     let track = Track.init(idFromAPI: idFromAPI, title: trackName, duration: duration, image: mainImageArtist!)
  234.                 track?.album = album
  235.                 track?.artist = artistObject
  236.                     addTrack(track!)
  237.                  self.favouriteTracksCollectionView.reloadInputViews()
  238.                  self.favouriteTracksCollectionView.reloadData()
  239.                 }
  240.             }
  241.             catch{
  242.                 print(error)
  243.             }
  244.         }
  245.            
  246.         fileprivate func addArtist(_ artist: Artist) {
  247.            favouriteArtists.append(artist)
  248.         }
  249.         fileprivate func addAlbum(_ album: Album) {
  250.             favouriteAlbums.append(album)
  251.         }
  252.         fileprivate func addTrack(_ track: Track) {
  253.             favouriteTracks.append(track)
  254.         }
  255.    
  256.     func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  257.         if collectionView == self.favouriteArtistsCollectionView {
  258.             artistIndex = indexPath.row
  259.             self.performSegue(withIdentifier: "FavouritesToArtistSegue", sender: self)
  260.  
  261.         }
  262.         if collectionView == self.favouriteAlbumsCollectionView {
  263.             albumIndex = indexPath.row
  264.             self.performSegue(withIdentifier: "FavouritesToAlbumSegue", sender: self)
  265.         }
  266.         else {
  267.             trackIndex = indexPath.row
  268.             self.performSegue(withIdentifier: "FavouritesToTrackSegue", sender: self)
  269.         }
  270.     }
  271.    
  272.     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  273.                if(segue.identifier == "FavouritesToArtistSegue") {
  274.                    let vc = segue.destination as! ArtistDetailsViewController
  275.                    vc.artist = favouriteArtists[artistIndex]
  276.                }
  277.                if(segue.identifier == "FavouritesToAlbumSegue") {
  278.                    let vc = segue.destination as! AlbumDetailsViewController
  279.                    vc.album = favouriteAlbums[albumIndex]
  280.                }
  281.                if(segue.identifier == "FavouritesToTrackSegue") {
  282.                    let vc = segue.destination as! TrackDetailsViewController
  283.                    vc.track = favouriteTracks[trackIndex]
  284.                }
  285.                
  286.            }
  287.        
  288.        
  289.     }
  290.  
  291.     extension UICollectionView {
  292.  
  293.         func setEmptyMessage(_ message: String) {
  294.             let messageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height))
  295.             messageLabel.text = message
  296.             messageLabel.textColor = .white
  297.             messageLabel.numberOfLines = 0;
  298.             messageLabel.textAlignment = .center;
  299.             messageLabel.font = UIFont(name: "TrebuchetMS", size: 15)
  300.             messageLabel.sizeToFit()
  301.  
  302.             self.backgroundView = messageLabel;
  303.         }
  304.  
  305.         func restore() {
  306.             self.backgroundView = nil
  307.         }
  308.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement