Filtering String from Firestore database sends an error on SwiftUI - filter

I'm working on implementing a search for a movies database stored in firestore using SwiftUI. I've tried doing filtering the movie names by the entered text as follows:
#ObservedObject var movies = getMoviesData()
...
ForEach(self.movies.datas) { movies in
ForEach(movies.title.filter({"\($0)".contains(searchText.lowercased()) || searchText.isEmpty})) { item in
if let url = URL(string: movies.img) {
AnimatedImage(url: url)
.resizable()
.frame(width: bounds.size.width / 2 - 0.6, height: bounds.size.height / 2 - 0.2)
}
}
.animation(.spring())
}
...
struct movies : Identifiable {
var id: String
var title: String
var img: String
var video: String
var description: String
var genre: String
}
class getMoviesData : ObservableObject{
#Published var datas = [movies]()
private var db = Firestore.firestore()
func fetchData(){
db.collection("movies").addSnapshotListener{ (querySnapshot, error) in
guard let mov = querySnapshot?.documents else{
print("No movies")
return
}
self.datas = mov.map{(queryDocumentSnapshot) -> movies in
let data = queryDocumentSnapshot.data()
let id = data["id"] as? String ?? ""
let title = data["title"] as? String ?? ""
let img = data["img"] as? String ?? ""
let video = data["video"] as? String ?? ""
let description = data["description"] as? String ?? ""
let genre = data["genre"] as? String ?? ""
return movies(id: id, title: title, img: img, video: video, description: description, genre: genre)
}
}
}
}
However, I'm receiving the following error on the second ForEach statement:
Referencing initializer 'init(_:content:)' on 'ForEach' requires that 'String.Element' (aka 'Character') conform to 'Identifiable'
Movies.title represents a String output of each movie identified in the ForEach statement. How should I filter movies.title against the provided search text without invoking this error?

I am little confused about your use of variable names.
ForEach(movies.title.filter({"\($0)".contains(searchText.lowercased()) || searchText.isEmpty})) { item in
}
}
In the above code movies.title is very misleading. Is there a title property on movies array. If you need to filter, you can perhaps check out the sample code below:
struct Movie {
let title: String
}
let movies = [Movie(title: "Spiderman"), Movie(title: "Batman"), Movie(title: "Superman")]
let searchWord = "batman"
let filteredMovies = movies.filter { movie in
return movie.title.lowercased().contains(searchWord.lowercased())
}
print(filteredMovies)

Related

swift 3 core data fetch results

i have a core data modal with the entity "Users"
There are two attributes "firstName" and "secondName"
this is actually my code to fetch the results:
var content:[String] = []
func RequestData() {
let appdelegate = NSApplication.shared().delegate as! AppDelegate
let context = appdelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Kunden")
request.returnsObjectsAsFaults = false
do {
let results = try context.fetch(request)
if results.count > 0 {
for result in results as! [NSManagedObject] {
if let firstname = result.value(forKey: "firstname") as? String {
content.append(firstname)
}
if let secondname = result.value(forKey: "secondname") as? String {
content.append(secondname)
}
}
}
tbl_kunden.reloadData()
} catch {
print("ERROR")
}
}
this works fine.
Problem is. I dont belive that
var content:[String] = []
is the correctly variable to take the results.
Because the output of print(content) is:
["Max", "Mustermann", "Max2", "Mustermann2", "Max3", "Mustermann3"]
Which variable type will be the best for this situation?
i think the result should be something like this:
+ID
++Max
++Mustermann
+ID
++Max2
++Mustermann2
+ID
++Max3
++Mustermann3
You should create custom User objects that are subclasses of NSManagedObject.
https://developer.apple.com/reference/coredata/nsmanagedobject
But if you don't need custom logic, you could change your variable to a Int:[String] Dictionary:
var content:[Int: [String]] = [:]
And append the data like this:
if let id = result.value(forKey: "firstname") as? Int {
let firstName = result.value(forKey: "firstname") as? String ?? "Unknown"
let secondName = result.value(forKey: "secondname") as? String ?? "Unknown"
let user = [id: [firstName, lastName]]
print("Fetched user: \(user.debugDescription)")
}

Filtering multiple times on one dictionary

I currently run this code:
searchterm = "test"
results = resultsArray.filter { $0.description.contains (searchterm!) }
My question is how do I search in company_name or place or any other field in my model and add it to the results.
Do I need to use filters together and then append the results to a new variable instance of my model?
EDIT:
If "test" is in company_name, place and description. I want all three results returned. However, if "test" is only in place, I need only place to be returned.
EDIT2:
This is an example of my model return. Is this a dictionary or an array? I'm sorry I dont 100% percent know the difference. I know ' "this": is ' what a dictionary looks like, however because there were [] brackets around them, I thought that made it an array...
struct GraphData {
var description: String
var company_name: String
var places: String
init(description: String, company_name: String, places: String){
self.description = description
self.company_name = company_name
self.places = places
}
func toAnyObject() -> Any {
print("return")
return [
"description": description,
"company_name": company_name,
"places": places,
]
}
The easiest way to do this would be to create a custom contains method in your model which can you can use to match the search term against any property in the model:
class YourModel {
var company_name: String
var description: String
var place: String
// ...
func contains(_ searchTerm: String) -> Bool {
return self.company_name.contains(searchTerm)
|| self.description.contains(searchTerm)
|| self.place.contains(searchTerm)
}
}
You can then simply filter using your custom method:
let searchTerm = "test"
let results = resultsArray.filter { $0.contains(searchTerm) }
Is this resultsArray a dictionary or an array?
You can do something like this
let searchTerm = "test"
let filter = resultsArray.filter{ $0.company_name!.contains(searchTerm) || $0.place!.contains(searchTerm) }
Edit
class TestClass: NSObject {
var place: String?
var company_name: String?
func contain(searchTerm: String) -> [String] {
var result = [String]()
if let placeVal = place, placeVal.contains(searchTerm) {
result.append(placeVal)
}
if let companyVal = company_name, companyVal.contains(searchTerm) {
result.append(companyVal)
}
return result
}
}
let searchTerm = "test"
let filter = resultsArray.map { $0.contain(searchTerm: searchTerm) }

Realm is returning an empty object when I convert it to an array

Using Realm in a Swift application. I'm fetching users from Realm and want to return an array of users (as my app also uses Parse, it's easier if they are all arrays I'm guessing).
Here is my code:
class func fetchUsersFromDB() -> [User]{
var users = [User]()
let realm = Realm()
var allUsers = realm.objects(User)
users = Array(allUsers)
return users
}
When I do a dump of allUsers I can see a Realm result. But when I dump users it shows me the object with default values.
Any ideas what I'm doing wrong?
Here is how I declare the User model
class User: Object {
dynamic var objectId: String = ""
dynamic var username: String = ""
dynamic var password: String = ""
dynamic var emailVerified: Bool = false
dynamic var email: String = ""
dynamic var firstName: String = ""
dynamic var defaultRelationshipId: String = ""
dynamic var picture: NSData = NSData()
dynamic var updatedAt: NSDate = NSDate()
dynamic var createdAd: NSDate = NSDate()
override static func primaryKey() -> String? {
return "objectId"
}
}

How to wait for a background function to finish before calling another one in swift?

I will try to explain briefly what the situation is.
I am building a quiz app and I wanted it to work mainly using the internet, but also to work for a while when the user is disconnected. The older code I was using was made only with synchronous queries, it was taking more time than what I expected. So i decided to reformulate it.
The situation I projected is the following:
When my user selects a subject the app will synchronously get 1 question for each subsubject in order to be ready for my user click and to be faster.
After getting this first question, the app would then get another 4 (or how much is needed to complete 5) for each of the subsubjects asynchronously, while the user is occupied answering the first question that was presented to him.
Finally, the app would save the objects in the local datastore, so that the user can answer 5 questions for each subsubject when he is not connected.
Here is my code:
func getQuestionsRemotelyandSave (subsubject:String?, subject:String?, arrayOfSubsubjects:[String]?) {
self.getFromUserDefaults()
if Reachability.isConnectedToNetwork() == true {
if self.needsToGetQuestions == true {
let user = PFUser.currentUser()
var query = PFQuery(className: "Questions")
query.whereKey("answeredBy", equalTo: user)
query.whereKey("grade", equalTo: user["grade"])
if subsubject != nil && subject == nil {
query.whereKey("subsubject", equalTo: subsubject)
query.limit = 2
let array = query.findObjects()
for item in array {
let object = item as PFObject
var QuestionToPin = PFObject(className: "Questions")
QuestionToPin["Question"] = object["Question"] as String
QuestionToPin["rightAnswer"] = object ["rightAnswer"] as String
QuestionToPin["wrongAnswer1"] = object ["wrongAnswer1"] as String
QuestionToPin["wrongAnswer2"] = object ["wrongAnswer2"] as String
QuestionToPin["wrongAnswer3"] = object ["wrongAnswer3"] as String
QuestionToPin["grade"] = object["grade"] as String
QuestionToPin["subject"] = object ["subject"] as String
QuestionToPin["subsubject"] = object ["subsubject"] as String
QuestionToPin["feedback"] = object ["feedback"] as? String
QuestionToPin["shortFeedback1"] = object ["shortFeedback1"] as? String
QuestionToPin["shortFeedback2"] = object ["shortFeedback2"] as? String
QuestionToPin["shortFeedback3"] = object ["shortFeedback3"] as? String
QuestionToPin.pin()
}
query.limit = 3
query.findObjectsInBackgroundWithBlock({ (objects:[AnyObject]!, error:NSError!) -> Void in
if error == nil {
let questions = objects as [PFObject]
var QuestionsToPin = [PFObject]()
for object in questions {
var QuestionToPin = PFObject(className: "Questions")
QuestionToPin["Question"] = object["Question"] as String
QuestionToPin["rightAnswer"] = object ["rightAnswer"] as String
QuestionToPin["wrongAnswer1"] = object ["wrongAnswer1"] as String
QuestionToPin["wrongAnswer2"] = object ["wrongAnswer2"] as String
QuestionToPin["wrongAnswer3"] = object ["wrongAnswer3"] as String
QuestionToPin["grade"] = object["grade"] as String
QuestionToPin["subject"] = object ["subject"] as String
QuestionToPin["subsubject"] = object ["subsubject"] as String
QuestionToPin["feedback"] = object ["feedback"] as? String
QuestionToPin["shortFeedback1"] = object ["shortFeedback1"] as? String
QuestionToPin["shortFeedback2"] = object ["shortFeedback2"] as? String
QuestionToPin["shortFeedback3"] = object ["shortFeedback3"] as? String
QuestionToPin.pinInBackground()
}
}
})
}
if subsubject == nil && subject != nil {
var firstTime = true
var semaphore = dispatch_semaphore_create(0)
query.limit = 1
for item in arrayOfSubsubjects! {
if item != "Todas as matérias" {
var query3 = PFQuery(className: "Questions")
query3.fromLocalDatastore()
query3.whereKey("subsubject", equalTo: item)
let count = query3.countObjects()
if count == 0 {
query.whereKey("subsubject", equalTo: item)
let array:NSArray = query.findObjects()
for item in array {
let object = item as PFObject
var QuestionToPin = PFObject(className: "Questions")
QuestionToPin["Question"] = object["Question"] as String
QuestionToPin["rightAnswer"] = object ["rightAnswer"] as String
QuestionToPin["wrongAnswer1"] = object ["wrongAnswer1"] as String
QuestionToPin["wrongAnswer2"] = object ["wrongAnswer2"] as String
QuestionToPin["wrongAnswer3"] = object ["wrongAnswer3"] as String
QuestionToPin["grade"] = object["grade"] as String
QuestionToPin["subject"] = object ["subject"] as String
QuestionToPin["subsubject"] = object ["subsubject"] as String
QuestionToPin["feedback"] = object ["feedback"] as? String
QuestionToPin["shortFeedback1"] = object ["shortFeedback1"] as? String
QuestionToPin["shortFeedback2"] = object ["shortFeedback2"] as? String
QuestionToPin["shortFeedback3"] = object ["shortFeedback3"] as? String
QuestionToPin.pin()
}
}
if count > 0 {
var limit = 5 - count
if limit < 0 {
limit = 0
}
query.limit = limit
if firstTime == false {
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
}
query.findObjectsInBackgroundWithBlock({ (objects:[AnyObject]!, error:NSError?) -> Void in
if error == nil {
let questions = objects as [PFObject]
for object in questions {
var QuestionToPin = PFObject(className: "Questions")
QuestionToPin["Question"] = object["Question"] as String
QuestionToPin["rightAnswer"] = object ["rightAnswer"] as String
QuestionToPin["wrongAnswer1"] = object ["wrongAnswer1"] as String
QuestionToPin["wrongAnswer2"] = object ["wrongAnswer2"] as String
QuestionToPin["wrongAnswer3"] = object ["wrongAnswer3"] as String
QuestionToPin["grade"] = object["grade"] as String
QuestionToPin["subject"] = object ["subject"] as String
QuestionToPin["subsubject"] = object ["subsubject"] as String
QuestionToPin["feedback"] = object ["feedback"] as? String
QuestionToPin["shortFeedback1"] = object ["shortFeedback1"] as? String
QuestionToPin["shortFeedback2"] = object ["shortFeedback2"] as? String
QuestionToPin["shortFeedback3"] = object ["shortFeedback3"] as? String
QuestionToPin.pinInBackground()
}
dispatch_semaphore_signal(semaphore)
firstTime = false
}
})
}
}
}
}
}
}
}
The problem I'm facing is that I cant request multiple asynchronous functions from Parse. What I thought was maybe waiting for an asynchronous function to finish before the other one starts, but I wanted it to happen without the user having to wait. Is there a way of doing it?
Thank you.

Signal SIGABRT in Swift using NSuserdefaults

I'm building a swift game and a need to set up a class. My code works for all the elements in my class, but not for this.
func saveInformationMember(){
var MembersDefaultName = NSUserDefaults.standardUserDefaults()
MembersDefaultName.setValue(globalCurrentMembers, forKey: "globalCurrentMembersData")
MembersDefaultName.synchronize()
}
GlobalCurrentMembers is an array of Member which looks like that:
class Member {
var image = String ()
var name = String ()
var progression = Int()
var round = Int()
var level = Int()
var imageProgression = [UIButton]()
func Init(){
image = "default.png"
name = "default"
progression = 0
round = 0
level = 0
}
To save your class this way, Member needs to conform to the NSCoding protocol.
Thx to Aaron Brager for is response. This is the response :
func saveInformationMember(){
let data = NSKeyedArchiver.archivedDataWithRootObject(globalCurrentMembers)
NSUserDefaults.standardUserDefaults().setObject(data, forKey: "member")}
func loadInformationMember(){
if let data = NSUserDefaults.standardUserDefaults().objectForKey("member") as? NSData {
globalCurrentMembers = NSKeyedUnarchiver.unarchiveObjectWithData(data) as [Member]
}
And my class:
class Member : NSObject, NSCoding {
var image = String ()
var name = String ()
var progression = Int()
var round = Int()
var level = Int()
var imageProgression = [UIButton]()
func initiation(){
image = "default.png"
name = "default"
progression = 0
round = 0
level = 0
}
required convenience init(coder decoder: NSCoder) {
self.init()
self.image = decoder.decodeObjectForKey("image") as String!
self.name = decoder.decodeObjectForKey("name") as String!
self.progression = decoder.decodeIntegerForKey("progression") as Int!
self.round = decoder.decodeIntegerForKey("round") as Int!
self.level = decoder.decodeIntegerForKey("level") as Int!
}
func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(self.image, forKey: "image")
coder.encodeObject(self.name, forKey: "name")
coder.encodeInt(Int32(self.progression), forKey: "progression")
coder.encodeInt(Int32(self.round), forKey: "round")
coder.encodeInt(Int32(self.level), forKey: "level")
}}

Resources