Xcode internal error when a certain line of code is insert - ios

I've been hunting down the source of this bug for a couple hours and I've found the line that causes it. The error is Xcode saying "An internal error occurred. source editor functionality limited" and all the syntax highlighting stops working. The error occurs whenever I typed about five or six keys or hit enter a couple of times.
After commenting and uncommenting code to find the problem, it turns out to be this line:
snapshot.value["string here"]
The weirdest thing is that I'm using that code here
// query server for a snapshot of current user's schedule
FirRef.child("\(user!.school)/students").queryOrderedByChild("email")
.queryEqualToValue("(userEmail!)").observeSingleEventOfType(.Value, withBlock: { snapshot in
if let data = snapshot.value as? [String: AnyObject]
{
// create new user model
let newUser = UserModel()
newUser.email = data["email"] as! String
newUser.school = data["school"] as! String
newUser.userId = data["userId"] as! String
newUser.title = ""
newUser.firstName = data["firstName"] as! String
newUser.lastName = data["lastName"] as! String
newUser.firstPeriod = data["firstPeriod"] as! String
newUser.secondPeriod = data["secondPeriod"] as! String
newUser.thirdPeriod = data["thirdPeriod"] as! String
newUser.fourthPeriod = data["fourthPeriod"] as! String
newUser.fifthPeriod = data["fifthPeriod"] as! String
newUser.sixthPeriod = data["sixthPeriod"] as! String
newUser.seventhPeriod = data["seventhPeriod"] as! String
}
})
and theres no issue but when I use this
// query server for snapshot of any teachers in the user's school
FirRef.child("\(user!.school)/teachers").observeSingleEventOfType(.Value, withBlock: { snapshot in
// iterate through all teachers found
for teacher in snapshot.children
{
// as soon as this line is put in
// Xcode wants to break itself
let thisBreaksStuff = teacher.value["exampleValue"]
}
The code runs perfectly well and retrieves the data I want from the server with no problem. But Xcode just doesn't like it.
Yes I have cleaned the project multiple times, restarted Xcode, restarted my computer. I've even deleted the derived data from Xcode as some people say to do

Related

How to get a specific string value out of a json response from firebase

I have this data structure and I can't extract the right value:
users
private
userID
birthday: "birthdayValue"
username: "nathan"
firstName: "Nathan"
etc...
I'm making a search feature in my app to search for users via their username through the firebase realtime database:
let reference = Database.database().reference()
if(searchText != ""){
reference.child("users").child("private").queryOrdered(byChild: "username").queryStarting(atValue: searchText).queryEnding(atValue: searchText + "\u{f8ff}").observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.value is NSNull{
//handles errors
return
}
else{
if let user = snapshot.value as? NSDictionary {
for child in user{
print(child.key)
print(child.value)
}
}
else{
//null
}
}
})
at the moment the two print statements are printing these two results in the console every time I search:
wnszfmHilqNl6PG9khWtWkKUPtF3
{
birthday = 100;
dateCreated = "1579543450313.94";
description = nil;
email = "email#email.com";
firstName = Nathan;
instagramLink = nil;
lastLogin = "1579543450313.988";
lastName = Ellis;
profilePicURL = "url";
twitchLink = nil;
username = nathan;
youtubeLink = nil;
}
Which is expected, it prints the usersID (the key) and the value of the snapshot as a NSDictonary. I'm only interested in getting the username, nothing else. How would I extract the username out of this firebase snapshot so I can add their username as a string to an array for my search controller?
Obviously it needs to be dynamic as the userID will always be different.
Would I need to change my data model?
Your child.value seems to be a dictionary as well, so you can access it by:
if let valueDict = child.value as? [String: AnyObject] {
if let username = valueDict["username"] as? String {
// append username to results
print(username)
}
}
To print just the username, the smallest possible change is:
print(resultsLocalArray["username"])
This will fine, but will still retrieve the entire user node to the client, which uses more bandwidth than strictly needed.
If you find yourself frequently needing just the username of a user, or maybe even a list of username values across users, you might want to consider storing a node with just user names. So something like:
users
userID: "nathan"
But in your current setup you only retrieve the node for a single user, so I doubt the bandwidth savings are worth the additional complexity.

Firebase is storing value even when user deleted it

I am struggling with the problem of storing the data. I am writing app that uses the firebase for authentication and as the database. The application works as scooter sharing. When user taps on one of the markers and taps on reserve button scooter is reserved by sending string value. It goes something like this:
I am tapping on reserve button
I am sendnig check value and user ID to selected scooter record as userKey
I am waiting for server response (feedback)
If there is response start reservation
If user change their mind and click on cancel button I am clearing the userKey and changing the status from Reserved to Off.
And there is a problem.
Even when I clear the userKey in appropriate scooter the function responsible for reservation can be still executed. For example when I simulate the server and I send feedback command to previously reserved scooter below code can be still executed even if the userKey is empty string. It doesn't happened to scooters that was not reserved yet. The main code goes like this:
func fetchScooters(){
ref?.child("service").child("scooters").observe(.value, with: { (snapshot) in
if snapshot.exists(){
let array:NSArray = snapshot.children.allObjects as NSArray
self.skutery = []
for child in array{
let snap = child as! DataSnapshot
if let dictionary = snap.value as? [String: Any] {
let skuter = ScooterInformation()
skuter.name = dictionary["name"] as? String
skuter.state = dictionary["state"] as? String
skuter.latitude = dictionary["latitude"] as? String
skuter.longitude = dictionary["longitude"] as? String
skuter.battery = dictionary["battery"] as? String
skuter.engine = dictionary["engine"] as? String
skuter.start = dictionary["start"] as? CLong
skuter.userKey = dictionary["userKey"] as? String
self.skutery.append(skuter)
if skuter.userKey == self.userID{
self.hideAllScootersIfUserReserved(scooterInfo: self.skutery)
// THERE IS SOMETHING WRONG....
self.handle = snap.ref.child("feedback").observe(.value, with: { (feedback) in
if let feedback = feedback.value as? Bool{
if feedback && skuter.userKey == self.userID{
print("Feedback received")
self.coundDown.invalidate()
self.timeToConnect = 20
snap.ref.child("feedback").removeValue()
snap.ref.child("check").removeValue()
if self.wantToRunScooter {
self.startScooter()
} else if self.userIsReservedScooter{
self.setStatusAsReserved()
self.userIsReservedScooter = false
}
}
}
})
By hitting the cancel button this is executed:
ref?.child("service").child("scooters").child("\(scooterNumber!)").child("state").setValue("*oF&")
ref?.child("service").child("scooters").child("\(scooterNumber!)").child("userKey").setValue("")
The handle function can be still executed even if the skuter.userKey is not equal to User ID because skuter.userKey should be empty string.
I am struggling with this second day and have no idea what is wrong with this..
I will be very grateful for any help.
Thanks
When the user hits the cancel button, your code only changes the state and the userKey but it does nothing to change the feedback value that is going to come back as true. You need to add something to change the feedback:
ref?.child("service").child("scooters").child("\(scooterNumber!)").child("feedback").setValue(false)
Plus you have:
if feedback && skuter.userKey == self.userID{ .... }
Isnt feedback a Bool and skuter.userKey a String? How can a Bool && String == String ?

Could not cast value of type 'SQLite.Blob' to 'Swift.Data'

This question relates to StephenCelis Sqlite library, so if someone has any idea about this, please share your fix. Though I have put my question on the issue tracker but haven't received any response yet, so I am also posting it here.
This is the function for creating DB record, which works fine.
public func createCandy(candy: Candy) throws
{
self.loadDb()
let db = try self.getDB()
let statement = try db.prepare("Insert INTO Candy(category, name, image, imageData) VALUES(?, ?, ?, ?)")
try statement.run(candy.category, candy.name, candy.image, candy.impageData.datatypeValue)
}
However, while retrieving data from Sqlite, I get the issue in the line candy.impageData = row[4] as? Data.
Following is the code for reading data
let candy = Candy()
candy.Id = row[0] as! Int64
candy.category = row[1] as? String
candy.name = row[2] as? String
candy.image = row[3] as? String
candy.impageData = row[4] as? Data
candies.append(candy)
This is the error message:
Could not cast value of type 'SQLite.Blob' to 'Swift.Data'
Just wondering what is the appropriate class in the library for casting this.

FetchRequst issue with data fault

When I was inserting data to one entity of CoreData, All the rows are inserted successfully(Saved).
But when I try to fetch the data using FetchRequest, Only one row of data is coming even if number of rows inserted are 3 or 4 or anything(more than 1).
Remaining rows are not getting fetched. And when I print fetch results,
It says - Error
0:<EquipmentDetails: 0x6000000bad60>
(entity: EquipmentDetails; id: 0xd000000000040000
coredata:/EquipmentDetails/p1> **data:fault>)**
I didn't get what was going in backend of core data?
code for Insertion
func insertEqipToLocalDb()
{
let mobileNo : String = UserDefaults.standard.string(forKey: "phoneNumber")!
let equipDetailsItem = NSEntityDescription.insertNewObject(forEntityName: "EquipmentDetails", into:managedObjContext) as! EquipmentDetails
for (index,item) in array_IDEquip.enumerated()
{
equipDetailsItem.mobileNumber = mobileNo
equipDetailsItem.type = array_typeEquip[index]
equipDetailsItem.name = array_nameEquip[index]
equipDetailsItem.startDate = array_sDateEquip[index]
equipDetailsItem.endDate = array_eDateEquip[index]
equipDetailsItem.equpID = Int16(item)
equipDetailsItem.serviceDatesStr = array_serviceDateEquip[index]
}
do
{
try managedObjContext.save()
UserDefaults.standard.set("AlreadyInstalled", forKey: "statusInstallation")
}
catch
{
Exception.insertExceptionDetails(errorMsg: error as NSError, context: managedObjContext)
}
}
//code for fetching
let request = NSFetchRequest<NSFetchRequestResult>()
let entity = NSEntityDescription.entity(forEntityName:"EquipmentDetails", in: managedObjContext)
request.entity = entity
do
{
let fetchResults = try managedObjContext.fetch(request)
for r in fetchResults
{
typeEquipArray.append((r as AnyObject).value(forKey: "type") as! String)
}
}
catch let error as NSError
{
Exception.insertExceptionDetails(errorMsg: error, context: managedObjContext)
}
On this line:
let equipDetailsItem = NSEntityDescription.insertNewObject(forEntityName: "EquipmentDetails", into:managedObjContext) as! EquipmentDetails
You create one instance. In the loop that follows, you set values for the type, name, etc properties over and over again on that same instance. Then you save changes, which include just that one object. If you want a difference instance of EquipmentDetails for each pass through the loop, you need to create the instance inside the loop.
The "fault" message is not an error unless you tried to access the property values and found that they were not present. It's part of how Core Data works. See the answer that Harshal Valanda linked in the comments for more detail.

How can I find a specific Product id by sending Product Name?

I use Firebase For My Store App. I want to find a Product's Details by taking a product name for the user. My JSON format looks like this:
{
product :
electronic =
a = {
pname = "iphone 5"
pprice = "20000"
pdescription = "Details....." }
b = {
pname = "iphone 6"
pprice = "30000"
pdescription = "Details....." }
}
cloths =
a = pname = "shirt"
pprice = "200"
pdescription = "Details....." }
b = {
pname = "pents"
pprice = "300"
pdescription = "Details....." }
}
Now, suppose I have the name iphone 5, then how can I find out the other details of the product?
Try this :-
FIRDatabase.database().reference().child("product/electronic").queryOrderedByChild("pname").queryEqualToValue("iphone 5").observeSingleEventOfType(.Value , withBlock : {(snap) in
if let snapDict = snap.value as? [String:AnyObject]{
for each in snapDict{
print(each.0) // product key
print(each.1) //product details
}
}
})
import Firebase
FIRApp.configure()
ref = FIRDatabase.database().reference()
let prod_query = "iphone 5"
ref.observeSingleEventOfType(.Value, withBlock: { (snapshot) in
let product_enum = snapshot.children
while let product = product_enum.nextObject() as? FDataSnapshot {
product.queryEqualToValue(child:"\(prod_query)").observeSingleEventOfType(.Value, withBlock: { (snap) in
let pid = snap.key as! String
let pprice = snap.value!["pprice"] as! Int
let pdescription = snap.value!["pdescription"] as! String
})
}
})
This implies that you know what the product letter is so that you can pull the correct name, price, and description.
The while loop will iterate through the different types of products (electronics, cloths, etc) and perform a query searching for a product ID that contains the child with the pname you're looking for.
Firebase suggests that instead of using .Value, it's better to use .ChildAdded since it accomplishes the same goal while managing new objects added. But since it appears you are trying to view static data, .Value works just fine.
This should serve as an excellent example as to how you can retrieve data using Firebase. But I suggest checking out the documentation on your own just in case you have further questions.
While I really don't mind looking this information up... this site is used in order to gain a better understanding of code, rather than existing as a collection of personal assistants.
Showing research efforts within your question can go a long way.

Resources