Post

Replies

Boosts

Views

Activity

Problem With Filter
I'm trying to filter my players using searchBar with scope in a collectionview using a switch statement and my case 0 works but the issue is my other cases I can type into the searchBar but I can't seem to filter (nothing shows up) nor can I delete all the characters when I type. I have 2 arrays my cPlayerArr is my original array when data is recieved and my allTextArr is my filtered array when any kind of filtering is done.    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {     allTextArr = cPlayerArr.filter({ player - Bool in       switch searchBar.selectedScopeButtonIndex {       case 0:         if searchText.isEmpty {           fetchAllPlayers()         } else {         return           player.yahooName!.lowercased().contains(searchText.lowercased())         }       case 1:         if searchText.isEmpty {           fetchForwards()         } else {           print(searchText)           return player.yahooName!.lowercased().contains(searchText.lowercased()) && player.position == "C" &&             player.position == "RW" && player.position == "LW"         }       case 2:         if searchText.isEmpty {           fetchDefense()         } else {           return player.yahooName!.lowercased().contains(searchText.lowercased()) && player.position == "D"         }       case 3:         if searchText.isEmpty {           fetchGoalies()         } else {           return player.yahooName!.lowercased().contains(searchText.lowercased()) && player.position == "G"         }       default:         return false       }       return true     })     collections.reloadData()   }    func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange: Int) {     if (searchBar.selectedScopeButtonIndex == 0) {       cPlayerArr.removeAll()       allTextArr.removeAll()       fetchAllPlayers()     } else if (searchBar.selectedScopeButtonIndex == 1) {       allTextArr.removeAll()       fetchForwards()     } else if (searchBar.selectedScopeButtonIndex == 2) {       allTextArr.removeAll()       fetchDefense()     } else {       allTextArr.removeAll()       fetchGoalies()     }   }    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) - Int {     if (searchBar.text != "" || searchBar.selectedScopeButtonIndex 0) {       return allTextArr.count     } else {       return cPlayerArr.count     }   }
14
0
1.1k
Apr ’21
The Core Data Save Button Problem
I am trying to have my favourites persist when the app gets terminated and relaunches using Core Data. I made a save button to do just that but it does not seem to save the data in the way I intended and I lose the data when the app relaunches I don't get an error message. Any help is appreciated. //this is my class for my favourites import CoreData enum DecoderConfigurationError: Error {   case missingManagedObjectContext } extension CodingUserInfoKey {   static let managedObjectContext = CodingUserInfoKey(rawValue: "managedObjectContext")! } @objc(CurrentPlayers) public class CurrentPlayers: NSManagedObject, Decodable {       enum CodingKeys: String, CodingKey {       case photoUrl = "PhotoUrl"       case firstName = "FirstName"       case lastName = "LastName"       case position = "Position"       case team = "Team"       case yahooName = "YahooName"       case status = "Status"       case jerseyNumber = "Jersey"     }          public static var managedObjectContext: NSManagedObjectContext?          required public convenience init(from decoder: Decoder) throws {       guard let context = decoder.userInfo[.managedObjectContext] as? NSManagedObjectContext else {         throw DecoderConfigurationError.missingManagedObjectContext       }             self.init(context: context)       //...      let values = try decoder.container(keyedBy: CodingKeys.self)      photoUrl = try values.decode(String.self, forKey: CodingKeys.photoUrl)      firstName = try values.decode(String.self, forKey: CodingKeys.firstName)      lastName = try values.decode(String.self, forKey: CodingKeys.lastName)      position = try values.decode(String.self, forKey: CodingKeys.position)      team = try values.decode(String.self, forKey: CodingKeys.team)      yahooName = try values.decodeIfPresent(String.self, forKey: CodingKeys.yahooName)      status = try values.decode(String.self, forKey: CodingKeys.status)      jerseyNumber = try values.decodeIfPresent(Int64.self, forKey: CodingKeys.jerseyNumber) ?? 0     } } //this is the class that has access to the saveContext class PersistenceService {       private init() {}           static var context: NSManagedObjectContext {       return persistentContainer.viewContext     } // MARK: CoreData static var persistentContainer: NSPersistentContainer = {   /*    The persistent container for the application. This implementation    creates and returns a container, having loaded the store for the    application to it. This property is optional since there are legitimate    error conditions that could cause the creation of the store to fail.   */   let container = NSPersistentContainer(name: "playerModel")   container.loadPersistentStores(completionHandler: { (storeDescription, error) in     if let error = error as NSError? {       // Replace this implementation with code to handle the error appropriately.       // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.               /*        Typical reasons for an error here include:        * The parent directory does not exist, cannot be created, or disallows writing.        * The persistent store is not accessible, due to permissions or data protection when the device is locked.        * The device is out of space.        * The store could not be migrated to the current model version.        Check the error message to determine what the actual problem was.        */       fatalError("Unresolved error \(error), \(error.userInfo)")     }   })   return container }() static func saveContext () {   let context = persistentContainer.viewContext   if context.hasChanges {     do {       try context.save()     } catch {       // Replace this implementation with code to handle the error appropriately.       // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.       let nserror = error as NSError       fatalError("Unresolved error \(nserror), \(nserror.userInfo)")     }   } } }    //this is my save button function   @IBAction func saveFav(_ sender: UIBarButtonItem) {     print("saved button pressed")     let saveFav = CurrentPlayers(context: context)     for o in favSet {     saveFav.yahooName = o.yahooName     saveFav.team = o.team     saveFav.position = o.position     saveFav.photoUrl = o.photoUrl     }     PersistenceService.saveContext()   }
2
0
1.1k
Aug ’21
Delete Cells From A Set
I'm trying to add delete functionality to my app and I am wondering how I can fix this error Cannot use mutating member on immutable value: 'favSet' is a get-only property. class FavouriteManager {           static let shared = FavouriteManager()       var favSet: OrderedSet<CurrentPlayers> = OrderedSet()       func add(_ player: CurrentPlayers) {     favSet.append(player)     NotificationCenter.default.post(       name: .passFavNotification,       object: player     )   } }    var favSet: OrderedSet<CurrentPlayers> {     FavouriteManager.shared.favSet   } //delete function    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {     if editingStyle == .delete {       tableView.beginUpdates()       favSet.remove(at: favSet.index(favSet.startIndex, offsetBy: indexPath.row)) //this is where the error is       tableView.deleteRows(at: [indexPath], with: .fade)       tableView.endUpdates()     }   }
7
0
798
Aug ’21
Adding Restores Everything
I have delete functionality in my app for favourites but when I delete a row but add another a favourite that row I just deleted is just added back to the top (gotta make sure that does not happen). I think this has to do with the notification. class FavouriteManager {           static let shared = FavouriteManager()     //it's an array now   var favArr : [CurrentPlayers] = []       var noRepFav : [CurrentPlayers] = []           func add(_ player: CurrentPlayers) {     favArr.append(player)     for player in favArr {       if !noRepFav.contains(player) {         noRepFav.append(player)       }     }     NotificationCenter.default.post(       name: .passFavNotification,       object: player     )   } } class FavouritesVC: UITableViewController {    var prefArr: Array<CurrentPlayers> {     get { FavouriteManager.shared.noRepFav }     set { FavouriteManager.shared.noRepFav = newValue }   }    @objc     func handleFavNotification(notification: Notification) {       tableView.reloadData()     }    //delete function    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {   if editingStyle == .delete {     tableView.beginUpdates()     prefArr.remove(at: indexPath.row)     tableView.deleteRows(at: [indexPath], with: .fade)     tableView.endUpdates()    }    } }
5
0
638
Aug ’21
Getting The Right Data Back
So I have an app and it relies on Core Data to save and load favourite players. The issue I have is the data being loaded in my viewwillappear method is the max number of all the players regardless whether or not I save the data. When I access my favouritesVC I can't go back and add more players because they take up the max amount of storage. I need my app to retrieve the favourites I saved not all the players. class FavouritesVC {    //this is a button I save my favourite players   //the print statements are accurate   @IBAction func save(_ sender: UIBarButtonItem) {     let entity = NSEntityDescription.entity(forEntityName: "CurrentPlayers", in: context)!     let saveFav = CurrentPlayers(entity: entity, insertInto: context)     for o in prefArr {       saveFav.yahooName = o.yahooName       saveFav.team = o.team       saveFav.position = o.position       saveFav.photoUrl = o.photoUrl     do {       try context.save()       print("These are my saved objects: \(saveFav)")       print("how many saved objects: \(prefArr.count)")     } catch {       print("error is: \(error)")     }     }   } } //what I use to load the data    override func viewWillAppear(_ animated: Bool) {     super.viewWillAppear(animated)     let fetchRequest = NSFetchRequest<CurrentPlayers>(entityName: "CurrentPlayers")     do {       prefArr = try context.fetch(fetchRequest)       for p in prefArr {         if p.yahooName == "Jordan Gross" {           print("Jordan added")         }       }       print("There are this many saved favourites \(prefArr.count)")     } catch let error {       print("Could not fetch. \(error)")     }   } } //core data class file import Foundation import CoreData enum DecoderConfigurationError: Error {   case missingManagedObjectContext } extension CodingUserInfoKey {   static let managedObjectContext = CodingUserInfoKey(rawValue: "managedObjectContext")! } @objc(CurrentPlayers) public class CurrentPlayers: NSManagedObject, Decodable {       enum CodingKeys: String, CodingKey {       case photoUrl = "PhotoUrl"       case firstName = "FirstName"       case lastName = "LastName"       case position = "Position"       case team = "Team"       case yahooName = "YahooName"       case status = "Status"       case jerseyNumber = "Jersey"     }          public static var managedObjectContext: NSManagedObjectContext?          required public convenience init(from decoder: Decoder) throws {       guard let context = decoder.userInfo[.managedObjectContext] as? NSManagedObjectContext else {         throw DecoderConfigurationError.missingManagedObjectContext       }             self.init(context: context)       //...      let values = try decoder.container(keyedBy: CodingKeys.self)      photoUrl = try values.decode(String.self, forKey: CodingKeys.photoUrl)      firstName = try values.decode(String.self, forKey: CodingKeys.firstName)      lastName = try values.decode(String.self, forKey: CodingKeys.lastName)      position = try values.decode(String.self, forKey: CodingKeys.position)      team = try values.decode(String.self, forKey: CodingKeys.team)      yahooName = try values.decodeIfPresent(String.self, forKey: CodingKeys.yahooName)      status = try values.decode(String.self, forKey: CodingKeys.status)      jerseyNumber = try values.decodeIfPresent(Int64.self, forKey: CodingKeys.jerseyNumber) ?? 0     } }
1
0
409
Sep ’21
Improve SearchBar
So I have a searchBar that works when you type in part of the name of a player or players and filters them but when you delete a character or more in the searchbar it does not show anything, I need help trying to add that as a condition in my func.  func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {     if searchText == "" {       parseJson()     } else if searchText != "" {       cPlayerArr = cPlayerArr.filter({ (player) -> Bool in return         player.yahooName.lowercased().contains(searchText.lowercased())       })     }     collections.reloadData()   }
9
0
783
Dec ’20
API Gives Me A Fuzzy Image
I'm trying to add an image to my project and I want it to take up most of the phone's screen but my issue is the resolution is very low and the image is fuzzy, the image is originally small but I am wondering if there are any tricks you can do with swift to make the resolution better at larger sizes. I tried a rounded image but that did not help me.
1
0
451
Jan ’21
Protocol Not Working
I'm trying to transfer a tableview cell from my hockeydetailVC to my favouritesVC using a button and I can't transfer it due to some issue. My hockeydetailVC protocol addThis {   func addFav(data: CurrentPlayers) } I'm trying to transfer my item object var item: CurrentPlayers?&#9;   var delegate: addThis? = nil&#9; func sendData() {     if delegate != nil {       let data = item!       delegate?.addFav(data: data)       print("This is the data being transferred: \(data)")     }   }       @IBAction func addToFav(_ sender: Any) {     sendData()     print("Favourite button Pressed")   } My favouritesVC  var currentFav: CurrentPlayers? func addFav(data: CurrentPlayers) {     currentFav = data   } I have a segue for my button so I have this   override func prepare(for segue: UIStoryboardSegue, sender: Any?) {   if segue.identifier == "r" {     let hockeyDetailVC: HockeyDetailVC = segue.destination as! HockeyDetailVC     hockeyDetailVC.delegate = self   }  } If the transfer works then my sendData() method up top would print a statement but my addToFav only prints "favourite button pressed".
19
0
1.2k
Feb ’21
Core Data Make Decodable
So I am using core data and I have to make my class Decodable to use the decoder for my get request. The errors I get are 'self' used in property access before 'super.init' call in my CoreDataClass each of my decode values has the error. CoreDataProperties extension CurrentPlayers {   @nonobjc public class func fetchRequest() - NSFetchRequestCurrentPlayers {     return NSFetchRequestCurrentPlayers(entityName: "CurrentPlayers")   }   @NSManaged public var photoUrl: String?   @NSManaged public var firstName: String?   @NSManaged public var lastName: String?   @NSManaged public var position: String?   @NSManaged public var team: String?   @NSManaged public var yahooName: String?   @NSManaged public var status: String?   @NSManaged public var jerseyNumber: Int64 } extension CurrentPlayers : Identifiable { } CoreDataClass @objc(CurrentPlayers) public class CurrentPlayers: NSManagedObject, Decodable {       enum CodingKeys: String, CodingKey {     case photoUrl = "PhotoUrl"     case firstName = "FirstName"     case lastName = "LastName"     case position = "Position"     case team = "Team"     case yahooName = "YahooName"     case status = "Status"     case jerseyNumber = "JerseyNumber"   }       required public init(from decoder: Decoder) throws {     let values = try decoder.container(keyedBy: CodingKeys.self)     photoUrl = try values.decode(String.self, forKey: CodingKeys.photoUrl)     firstName = try values.decode(String.self, forKey: CodingKeys.firstName)     lastName = try values.decode(String.self, forKey: CodingKeys.lastName)     position = try values.decode(String.self, forKey: CodingKeys.position)     team = try values.decode(String.self, forKey: CodingKeys.team)     yahooName = try values.decode(String.self, forKey: CodingKeys.yahooName)     status = try values.decode(String.self, forKey: CodingKeys.status)     jerseyNumber = Int64(try values.decode(Int.self, forKey: CodingKeys.jerseyNumber))   } }
12
0
3.3k
Mar ’21
Pod Error
I downloaded the pod "youtube-ios-player-helper", "~ 1.0.3" and minutes after importing it I get the error No such module 'youtube_ios_player_helper'. Did I install the pod correctly? podfile target 'LearnHockey' do  use_frameworks!  pod "youtube-ios-player-helper", "~ 1.0.3" end
1
0
704
Mar ’21
Remove Empty Names
I'm trying to find a way to remove instances of empty names in my array. I was trying to find the indices to remove them but it does not print. I could use a little help.    func filterArr() {     for (index, player) in cPlayerArr.enumerated() {       if (player.yahooName == "") {         print("Found \(player) at \(index)")       }     }   } extension CurrentPlayers {   @nonobjc public class func fetchRequest() - NSFetchRequestCurrentPlayers {     return NSFetchRequestCurrentPlayers(entityName: "CurrentPlayers")   }   @NSManaged public var photoUrl: String?   @NSManaged public var firstName: String?   @NSManaged public var lastName: String?   @NSManaged public var position: String?   @NSManaged public var team: String?   @NSManaged public var yahooName: String?   @NSManaged public var status: String?   @NSManaged public var jerseyNumber: Int64 } extension CurrentPlayers : Identifiable { }
3
0
424
Mar ’21