Access one to many CoreData with predicate - sqlite

I have an one-to-many database (Questions--->>Buttons)
I am stuck here as I don't know how to proceed with this to access the buttons from my database:
I have the following code that I can get to my Questions Entity but I don't know how to proceed from here. Thanks
func presentQuestionDetails(questionID :Int) {
let coreDataStack = CoreDataStack()
managedObjectContext = coreDataStack.persistentContainer.viewContext
let fetchRequest: NSFetchRequest<Questions> = Questions.fetchRequest()
let myPredicate = NSPredicate(format: "%K == %i", "questionID", questionID)
fetchRequest.predicate = myPredicate
do {
let results = try managedObjectContext!.fetch(fetchRequest)
if results.isEmpty {
//empty
print("empty")
}
else {
let question = results[0]
//do something
print("got something")
questionLabel.text = question.questionTitle
for _ in 0..<(question.buttons?.count)! {
//I'D LIKE TO LOOP THROUGH MY BUTTONS HERE AND ACCESS MY "buttonTitle" i.e print(buttons.buttonTitle!)
}
}
} 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)")
}
}

Would that be the correct way? I am only guessing and would like your input.
It seems to provide the right outcome but I am not sure if this is the right way to do it...
thanks
[...]
else {
let question = results[0]
//do something
print("got something")
questionLabel.text = question.questionTitle
let fetchRequest: NSFetchRequest<Buttons> = Buttons.fetchRequest()
let myPredicate = NSPredicate(format: "%K == %i", "questions", questionID)
fetchRequest.predicate = myPredicate
do {
let results = try managedObjectContext!.fetch(fetchRequest)
for buttons in results {
print(buttons.buttonTitle!)
}
}
catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}

Related

How to use runTransaction with firebase_database 9.0.3

Can anyone give where to look, or what I am missing, for how to use runTransaction in 9.0.3? (Flutter, Firebase realtime DB)
I updated firebase_database ^7.0.0 to ^9.0.3. Had to change runTransaction(MutableData mutable) to runTransaction(Object object), and the Object is null for Map data. Does return a String when point to single node of a String.
For something to work I placed + ‘/sap’ at end of .ref(…), and it gave ‘DROID’
Code Updated for Comment below:
bool bCanWeStartGame = false;
bool bIfiOS = false;
bIfiOS = Theme.of(referencedData.mngGamesPageMaterialContext)
.platform == TargetPlatform.iOS;
DatabaseReference playersRef = referencedData.database.ref(
TABLENAME_STARTS + '/' + referencedData.strFBGameUniqueIDKey);
if(bIfiOS){
//apparently iPhone needs to 'open line to DB record' to work
playersRef.once()
.then((DatabaseEvent event) {//dont need to do anything??
});
}
TransactionResult txResult;
//while loop to repeat runTransaction until solved
int iWhileLoopCheck = 0; //so whileLoop does not go forever
bool bTransactionCommittedOrGetOutAnyWay = false;
while(!bTransactionCommittedOrGetOutAnyWay
&& (iWhileLoopCheck<30)){
iWhileLoopCheck++;
txResult = await playersRef
.runTransaction(
(Object post) {
if (post == null) {
if(bIfiOS){sleep(Duration(milliseconds: 3));}
return Transaction.abort(); //out, but will retry transaction
}
Map<String, dynamic> _post = Map<String, dynamic>.from(post as Map);
bTransactionCommittedOrGetOutAnyWay = true; //whichever of
//options below take effect, dont want to continue while loop
if (_post[STARTS_TABLE_ALL_PLAYERS] !=
startingGames[iIndexInStartingGames].allplayers) {
//someone has joined since trying to start
bCanWeStartGame = false;
//Transaction.abort() as dont want to change data
return Transaction.abort();
} else {
//Nobody has joined, so can Start. Tell others Game is starting
_post['stg'] = true;
bCanWeStartGame = true;
return Transaction.success(_post);
}
});
} //while runtransaction doesnot get at data```

Checking if username already exists gives error kotlin

I translated the code below from java, but I am getting an error in some places, why is it giving an error, is there a point I missed?
val mQuery: Query = firestore.collection("users")
.whereEqualTo("nickname", mUserName)
mQuery.addSnapshotListener(object : EventListener<QuerySnapshot> {
fun onEvent(
documentSnapshots: QuerySnapshot,
e: FirebaseFirestoreException?
) {
for (ds in documentSnapshots) {
if (ds != null) {
val userName: String = document.getString("username")
Log.d(
TAG,
"checkingIfusernameExist: FOUND A MATCH: $userName"
)
Toast.makeText(
this#SignUpActivity,
"That username already exists.",
Toast.LENGTH_SHORT
).show()
}
}
}
})
I've been doing the things described here for 2-3 days, but it keeps throwing an error.Event listeners and docs throw errors.
I translated the code below from java
That's not the correct way of "translating" that code from Java to Kotlin, since that answer provides a solution for getting data only once. So to be able to do that in Kolin programming language please use the following lines of code:
val rootRef = FirebaseFirestore.getInstance()
val allUsersRef = rootRef.collection("all_users")
val userNameQuery = allUsersRef.whereEqualTo("username", "userNameToCompare")
userNameQuery.get().addOnCompleteListener { task ->
if (task.isSuccessful) {
for (document in task.result) {
if (document.exists()) {
Log.d("TAG", "username already exists")
val userName = document.getString("username")
//Do what you need to do with the userName
} else {
Log.d("TAG", "username does not exists")
}
}
} else {
Log.d("TAG", "Error getting documents: ", task.exception)
}
}

UnsafeMutablePointer usage in Swift 3

I am using the following extension for UIBezierPath:
extension UIBezierPath {
var elements: [PathElement] {
var pathElements = [PathElement]()
withUnsafeMutablePointer(&pathElements) { elementsPointer in
CGPathApply(CGPath, elementsPointer) { (userInfo, nextElementPointer) in
let nextElement = PathElement(element: nextElementPointer.memory)
let elementsPointer = UnsafeMutablePointer<[PathElement]>(userInfo)
elementsPointer.memory.append(nextElement)
}
}
return pathElements
}
}
This is from the site:
https://oleb.net/blog/2015/06/c-callbacks-in-swift/
However, this breaks with Swift 3 for the following line:
let elementsPointer = UnsafeMutablePointer<[PathElement]>(userInfo)
Following error is displayed:
Cannot invade initializer for type 'UnsafeMutablePointer<[PathElement]>' with an argument list of type '(UnsafeMutableRawPointer?)'
I understand that this is related to the change in Swift 3:UnsafeRawPointerMigration
https://swift.org/migration-guide/se-0107-migrate.html
However, I am not quite sure the best way to port this to Swift 3. Would you be able to provide some help in this regard w/ updated code for the above extension?
I reached out Ole Begemann directly regarding this question. He was very helpful and promptly provided updated code that works with Swift 3. Sharing the same if someone else runs into the same issue as well.
This should work:
extension UIBezierPath {
var elements: [PathElement] {
var pathElements = [PathElement]()
withUnsafeMutablePointer(to: &pathElements) { elementsPointer in
let rawElementsPointer = UnsafeMutableRawPointer(elementsPointer)
cgPath.apply(info: rawElementsPointer) { userInfo, nextElementPointer in
let nextElement = PathElement(element: nextElementPointer.pointee)
let elementsPointer = userInfo?.assumingMemoryBound(to: [PathElement].self)
elementsPointer?.pointee.append(nextElement)
}
}
return pathElements
}
}

CMBlockBuffer, UnsafeMutablePointer et al in Swift

I am trying to convert some Objective C code provided in one of Apple's code examples here: https://developer.apple.com/library/mac/samplecode/avsubtitleswriterOSX/Listings/avsubtitleswriter_SubtitlesTextReader_m.html
The result I have come up with thus far is as follows:
func copySampleBuffer() -> CMSampleBuffer? {
var textLength : Int = 0
var sampleSize : Int = 0
if (text != nil) {
textLength = text!.characters.count
sampleSize = text!.lengthOfBytesUsingEncoding(NSUTF16StringEncoding)
}
var sampleData = [UInt8]()
// Append text length
sampleData.append(UInt16(textLength).hiByte())
sampleData.append(UInt16(textLength).loByte())
// Append the text
for char in (text?.utf16)! {
sampleData.append(char.bigEndian.hiByte())
sampleData.append(char.bigEndian.loByte())
}
if (self.forced) {
// TODO
}
let samplePtr = UnsafeMutablePointer<[UInt8]>.alloc(1)
samplePtr.memory = sampleData
var sampleTiming = CMSampleTimingInfo()
sampleTiming.duration = self.timeRange.duration;
sampleTiming.presentationTimeStamp = self.timeRange.start;
sampleTiming.decodeTimeStamp = kCMTimeInvalid;
let formatDescription = copyFormatDescription()
let dataBufferUMP = UnsafeMutablePointer<Optional<CMBlockBuffer>>.alloc(1)
CMBlockBufferCreateWithMemoryBlock(kCFAllocatorDefault, samplePtr, sampleSize, kCFAllocatorMalloc, nil, 0, sampleSize, 0, dataBufferUMP);
let sampleBufferUMP = UnsafeMutablePointer<Optional<CMSampleBuffer>>.alloc(1)
CMSampleBufferCreate(kCFAllocatorDefault, dataBufferUMP.memory, true, nil, nil, formatDescription, 1, 1, &sampleTiming, 1, &sampleSize, sampleBufferUMP);
let sampleBuffer = sampleBufferUMP.memory
sampleBufferUMP.destroy()
sampleBufferUMP.dealloc(1)
dataBufferUMP.destroy()
dataBufferUMP.dealloc(1)
samplePtr.destroy()
//Crash if I call dealloc here
//Error is: error for object 0x10071e400: pointer being freed was not allocated
//samplePtr.dealloc(1)
return sampleBuffer;
}
I would like to avoid the "Unsafe*" types where possible, though I am not sure it is possible here. I also looked at using a struct and then somehow seeing to pack it somehow, but example I see seem to be based of sizeof, which uses the size of the definition, rather than the current size of the structure. This would have been the structure I would have used:
struct SubtitleAtom {
var length : UInt16
var text : [UInt16]
var forced : Bool?
}
Any advice on most suitable Swift 2 code for this function would be appreciated.
so, at first, you code use this pattern
class C { deinit { print("I got deinit'd!") } }
struct S { var objectRef:AnyObject? }
func foo() {
let ptr = UnsafeMutablePointer<S>.alloc(1)
let o = C()
let fancy = S(objectRef: o)
ptr.memory = fancy
ptr.destroy() //deinit runs here!
ptr.dealloc(1) //don't leak memory
}
// soon or later this code should crash :-)
(1..<1000).forEach{ i in
foo()
print(i)
}
Try it in a playground and most likely it crash :-). What's wrong with it? The trouble is your unbalanced retain / release cycles. How to write the same in the safe manner? You removed dealloc part. But try to do it in my snippet and see the result. The code crash again :-). The only safe way is to properly initialize and de-ininitialize (destroy) the underlying ptr's Memory as you can see in next snippet
class C { deinit { print("I got deinit'd!") } }
struct S { var objectRef:AnyObject? }
func foo() {
let ptr = UnsafeMutablePointer<S>.alloc(1)
let o = C()
let fancy = S(objectRef: o)
ptr.initialize(fancy)
ptr.destroy()
ptr.dealloc(1)
}
(1..<1000).forEach{ i in
foo()
print(i)
}
Now the code is executed as expected and all retain / release cycles are balanced.

NSXMLParser Failed to parse data on watch but working fine on watch simulator

NSXMLParser Failed to parse data on watch but working fine on watch simulator.How to resolve this issue?
Kindly help
Here is Code:
let url:String="http://www.someurl.com/data"
let urlToSend: NSURL = NSURL(string: url)!
// Parse the XML
parser = NSXMLParser(contentsOfURL: urlToSend)!
parser.delegate = self
let success:Bool = parser.parse()
if success {
print("parse success!")
print(strXMLData)
} else {
print("parse failure!")
}
I've experienced the same issue, and I couldn't debug the app when running on the watch. My solution was to parse the XML file in the iPhone App side and communicate the data to the watch through a WCSession.
I had exactly the same problem. I found an answer on one of Apple's own forums.
You need to read in the XML from URL into NSData, then invoke XML parser with NSData object, not the NSURL.
Here is some code
var nsXMLData = NSData()
var parser = NSXMLParser()
func xmlFileRequest(urlweb:NSURL){
print("in xmlFileRequest")
let requestURL: NSURL = urlweb
let urlRequest: NSMutableURLRequest =
NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
if error == nil {
print(">>>>>>xmlFileRequest success!")
self.nsXMLData = data!
self.beginParsing()
} else {
print(">>>>>>>xmlFileRequest fail")
}
}
task.resume()
}
func beginParsing()
{
parser = NSXMLParser.init(data:nsXMLData)
parser.delegate = self
let success:Bool = parser.parse()
if success {
print("***parse success***")
} else {
print("***parse failure!***")
let errorMsg:String =
(parser.parserError?.localizedDescription)!
print("Error = " + errorMsg)
}
}
I just tested this code on our Apple watch.

Resources