simple data insertion using realm swift - ios

I'm an newbie in realm-swift. Trying to do an simple data insertion in realm DB.
I'm getting following warning:-
WARNING: An RLMRealm instance was deallocated during a write transaction and
all pending changes have been rolled back. Make sure to retain a reference
to the RLMRealm for the duration of the write transaction.
Here is my code :-
//
// Dog.swift
// RealmDemo
//
// Created by RIPA SAHA on 20/07/16.
// Copyright © 2016 RIPA SAHA. All rights reserved.
//
import Foundation
class Dog {
dynamic var name = ""
dynamic var age = ""
}
//
// ViewController.swift
// RealmDemo
//
// Created by RIPA SAHA on 19/07/16.
// Copyright © 2016 RIPA SAHA. All rights reserved.
//
import UIKit
import RealmSwift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let myDog = Dog()
myDog.name = "puppies"
myDog.age = "5"
// Get the default Realm
let realm = try! Realm()
// Add to the Realm inside a transaction
realm.beginWrite()
realm.add(myDog)
/*realm.add(myDog)
realm.commitWrite()*/
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
any help would be appreciated...

Follow this example:
import Foundation
import RealmSwift
class Dog : Object {
dynamic var name = ""
dynamic var age = ""
}

Wrap your write code as follow:
try! realm.write {
realm.add(myDog)
}
This should fix the problem

Related

How to get RealmSwift working with Xcode 11?

I've been trying to get started with Realm (version 4.3.0) as a database option with Xcode 11. With my Googling skills I could not get an answer for my problems. I've tried to use the Official Realm documentation but it appears that the way they do things is not working with Xcode 11. Basic code:
import UIKit
import RealmSwift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
class Test: Object {
#objc dynamic var text = ""
#objc dynamic var internalId = 0
}
let newTest = Test()
newTest.text = "Text" // Errors happen here
print("text: \(newTest.text)")
}
I get an errors that I definitely was not expecting:
Consecutive declarations on a line must be separated by ';'
Expected '(' in argument list of function declaration
Expected '{' in body of function declaration
Expected 'func' keyword in instance method declaration
Expected declaration
Invalid redeclaration of 'newTest()'
Also when I'm trying to initialize and write to Realm with:
let realm = try! Realm()
try! realm.write { // Error here
realm.add(newTest)
}
I get the error of "Expected declaration"
From what I've read, Realm seems like a really nice database option for iOS, but with these problems, I cannot get up and running. Any help would be greatly appreciated.
Let's rearrange the code so the objects and functions are in their correct place.
import UIKit
import RealmSwift
//this makes the class available throughout the app
class Test: Object {
#objc dynamic var text = ""
#objc dynamic var internalId = 0
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//create a new realm object in memory
let newTest = Test()
newTest.text = "Text"
print("text: \(newTest.text)")
//persist the object to realm
let realm = try! Realm()
try! realm.write {
realm.add(newTest)
}
//or read objects
let results = realm.objects(Test.self)
for object in results {
print(object.text)
}
}
}
Like #108g commented:
I was trying to create an instance at class level. So I moved the creation, modification and the print inside viewDidLoad() method. Then I moved my Test class into a new file.
So the code that works:
ViewController.swift
import UIKit
import RealmSwift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let newTest = Prompt()
newTest.text = "Text"
print("text: \(newTest.text)")
let realm = try! Realm()
try! realm.write {
realm.add(newTest)
}
}
}
And RealmTest.swift (new file)
import Foundation
import RealmSwift
class Prompt: Object {
#objc dynamic var text = ""
#objc dynamic var internalId = 0
}

iOS web view error

Im trying to play a Youtube video in my app with the Webview
the build is succsesful but when i run the app it shows all white and i get this error: Thread 1:EXC_BAD_INSTRUCTION(code=EXC_I1386_INVOP,subcode=0x0)
it happenes on the Youtube.loadRequest(URLRequest(url:url!))
//
// ViewController.swift
// CFBC
//
// Created by KWIA on 6/6/17.
// Copyright © 2017 KWIA. All rights reserved.
//
import UIKit
import Firebase
class ViewController: UIViewController {
#IBOutlet weak var Youtube: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
getVideo(videoCode: "RmHqOSrkZnk")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getVideo(videoCode:String)
{
let url = URL(string: "https//www.youtube.com/embed/\(videoCode)")
Youtube.loadRequest(URLRequest(url: url!))
}
}
Your URL is not valid, you are missing : after https.
It should be: "https://www.youtube.com/embed/\(videoCode)"
That leads to URL(string:) returning nil and to a crash when you try to force unwrap it using !.

FIRDatabaseReference returns nil, UserID retrievable though

I'm trying to retrieve data from my Firebase database, but I'm stuck at the database reference returning nil. However, I successfully can retrieve the UserID, so I don't think it's not properly connected to my database:
import UIKit
import Firebase
import FirebaseDatabaseUI
class LoggedInViewController: UIViewController {
var ref: FIRDatabaseReference!
let userid = FIRAuth.auth()?.currentUser?.uid
override func viewDidLoad() {
super.viewDidLoad()
UIDLabel.text = String((userid)!) // The Label shows the UID
reflabel.text = String(ref) // The Label shows "nil"
}
}
My goal is to retrieve data from the path using this method:
func getQuery() -> FIRDatabaseQuery {
let myTopPostsQuery = (ref.child("user-posts")).child(getUid()))
return myTopPostsQuery
}
But obviously this doesn't work since I'm getting an error because of the nil reference.
In viewDidLoad use FIRDatabase.database().reference()
override func viewDidLoad() {
super.viewDidLoad()
self.ref = FIRDatabase.database().reference()
//....
}

Custom Address Search iOS mapkit

Learning swift 2/ Xcode 7 and creating a app iOS 9 where I can enter a custom address. I have mapkit working and can search regular address. I have my current location working. Instead of entering an address: "Number,Street, city, zip code", I want the user to enter: PR33.1 for example, and that would show the user that location. I have the long and lats for the custom address's, I've read many things on geocoding and annotations but nothing that would let me accomplish what I need. Can this be done? jSon file maybe.. I'm really new at this...
thanks
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var textField: UITextField!
let arbitraryString: [String:String] =
["161 RL2": "23908709138882,-106.7433588579297",
"40.9 RL112":"32.393144,-106.727762"]
#IBAction func enterButtonTapped(sender: AnyObject) {
if let textField = arbitraryString["161 RL2"] {
print(" \(textField).")
} else {
print("That is not in the dictionary.")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

how to get key of selected value from nsdictionary

I am using NSDictionary to get data from json and then i added the value from NSDictionary to UITableView.When user is selected one of the table cell it will send back the value.The point is how to get the key of selected value from table cell in NSDictionary in Swift?
import UIKit
class ViewController: UIViewController {
var myFruits = ["0_22":"Sunkist","34_22":"Pine Apple","45_22":"Grape","1_123":"Apple"]
override func viewDidLoad() {
super.viewDidLoad()
// If my selected key is "Sunkist, what do i need to to get its value (0_22)"
// Any Code Help?
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
This code will work fine.
var myFruits = ["0_22":"Sunkist","34_22":"Pine Apple","45_22":"Grape","1_123":"Apple"]
var dic:NSDictionary = NSDictionary(dictionary:myFruits)
println(dic.allKeysForObject("Sunkist"))
Thanks for #Martin R who give me that answer.I got this now with that code
let keys = (myFruits as NSDictionary).allKeysForObject("Sunkist")
println(String(keys[0] as! NSString))
Output is
0_22

Resources