Error when I tried to read and write from Realm objects - ios

I'm trying Realm for the first time but I'm getting errors when I tried to read and write from Realm, here is the code with the error lines commented:
class Test{
dynamic var name = ""
}
class ViewController: UIViewController {
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.
}
#IBOutlet weak var label: UILabel!
#IBAction func show(sender: UIButton){
let test = Realm().objects(Test) //cannot invoke 'objects' with no arguments
label.text = test.name
}
#IBAction func set(sender: UIButton){
let test = Test()
let realm = Realm()
test.name = "not using CoreData"
realm.write{realm.add(test)} //cannot invoke write with argument list of type (()->_)
}
}
here is the documentation page if anyone is interested: https://realm.io/docs/swift/latest/

Can you try changing you declaration of the Test class to the following?
class Test : Object

Related

Use data from a scope outside of the scope

I am trying to use a text from a website in an iPhone app. To do that I use a web scraper , Osmosis. I managed to retrieve the data I wanted but I can't affect the data to an array, in order to use it outside of the function. Here's a snippet of what I did:
<language: lang-swift>
class ViewController: UIViewController {
#IBOutlet weak var quote: UILabel!
private var array: [[String: AnyObject]] = []
var initArray: [[String: AnyObject]] {
get {
return array
}
set {
for e in self.initArray {
array.append(e)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
getQuotes()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getQuotes()
Osmosis(errorHandler: { (error) -> Void in
print(error)
})
.get(NSURL(string: "http://www.example.com")!)
.find(OsmosisSelector(selector: ".parentDiv"), type: .CSS)
.populate([
OsmosisPopulateKey.Single("quotes") : OsmosisSelector(selector: ".childDiv")
], type: .CSS)
.list { (dict) -> Void in
self.array.append(dict)
print(self.initArray) // this prints data
}
.start()
print(self.initArray) // This prints an empty array
}
}
I think I can't use the array because it is filled inside the init of Osmosis() but I wonder how to use it somewhere else in my code. Can you please explain what happens in my code (why can I use the data only in .list()) and how to fix that.
Edit:
I tried to use a getter and a setter in order to retrieve my data outside of the scope, but the result is the same as if there were no getter/setter.
you want to add all elements of one array to another array?
for e in quotesArray {
self.array.append(e)
}
or
self.array.appendContentsOf(quotesArray)
Based on Christian Dietrich's answer and comments, I managed to fix my issue by updating the UI inside my scope.
Here's what I did:
import UIKit
import Osmosis
class ViewController: UIViewController {
#IBOutlet weak var quote: UILabel!
var array: [[String: AnyObject]] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
getQuotes()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getQuotes() {
var updateText: String = ""
Osmosis(errorHandler: { (error) -> Void in
print(error)
})
.get(NSURL(string: "http://www.exemple.com")!)
.find(OsmosisSelector(selector: ".wrapper"), type: .CSS)
.populate([
OsmosisPopulateKey.Single("div") : OsmosisSelector(selector: ".div")
], type: .CSS)
.list { (dict) -> Void in
self.array.append(dict)
updateText = self.array[0]["div"] as! String
self.quote.text = updateText
self.view.setNeedsDisplay()
}
.start()
}
}
Thanks for your help !

Missing Argument for parameter #1 in call error

I'm new in this website, and I already know that it helps me a LOT in coding, so thanks to the founder of this website and to the questioners and the answerers and everyone else :D
Still, one problem I have though. I have this 'Missing Argument for Parameter #1 in call' error. Its really annoying me, I'm trying to make an app, and for how much time I put into this app, I don't want to delete it. Please.
So here is the code:
class ViewController: UIViewController {
#IBOutlet var UsernameTextField: UITextField!
#IBOutlet var PasswordTextField: UITextField!
#IBOutlet var EmailTextField: UITextField!
#IBAction func LogIn(sender: AnyObject) {
}
#IBAction func SignUp(sender: AnyObject) {
SignUp() //The error is here
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
func SignUp(){
var user = PFUser()
user.username = UsernameTextField.text
user.password = PasswordTextField.text
user.email = EmailTextField.text
}
let user = PFUser()
user.username = "Name:"
user.password = "Pass:"
user.email = "Email:"
user.signUpInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in
if error == nil {
// Hooray! Let them use the app now.
} else {
// Examine the error object and inform the user.
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You've got two functions with the same name, you should rename one of them!
First function:
#IBAction func SignUp(sender: AnyObject)
Second function:
func SignUp()
The reason you get the error is because the compiler is trying to use your first function rather than the second one, so the easiest way to fix it is to change the name of one of the functions.

unexpectedly found nil while unwrapping an Optional value (swift)

I get the error in the title while trying to change the text of a label which is part of the Page class (a subclass of UIViewController)
#IBAction func StartButton(sender: AnyObject) {
for quote in quoteList {
var newPage = Page()
//error is on the next line:
newPage.Label.text = quote
pageArray!.append(newPage)
}
}
}
and here is the Page class:
class Page : UIViewController{
var index: Int = 0
var parent: PageArray?
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.
}
#IBOutlet weak var Label: UILabel!
#IBAction func previousButton(sender: AnyObject) {
}
#IBAction func gotoListButton(sender: AnyObject) {
}
#IBAction func nextButton(sender: AnyObject) {
}
}
I am new when it comes to swift programming, and iOs in general; I apologise if a similar question has already been asked. I searched first, but didn't find a solution that worked for me.
I suspect the problem is with the initialization of newPage, and tried doing it a few different ways, but I can't seem to get it right.
My question is what exactly am I doing wrong, and how can I fix it?
EDIT: Got it working like this (by working I mean not crashing and doing nothing):
#IBAction func StartButton(sender: AnyObject) {
var pageArray: PageArray = PageArray()
for quote in quoteList {
var newPage = Page(nibName: "Page", bundle: nil)
if newPage.Label != nil {
newPage.Label.text = quote
}
pageArray.append(newPage)
}
}
It seems certain now that newPage.Label is nil.
Well, pageArray is probably nil and with ! you are pretending that it is not.
Instantiating pageArray should solve your issue.
You can check the first answer here to learn more about question and exclamation marks in swift
EDIT:
Your problem might also come from your controller initialization, you might want to try:
let mystoryboard:UIStoryboard = UIStoryboard(name: "storyboardName", bundle: nil)
var newPage:Page = mystoryboard.instantiateViewControllerWithIdentifier("idYouAssigned") as! Page
I knew your problems. When you load a ViewController from Nib. Actually It's take a delay time until your ViewController has been loaded.
This code below help your ViewController load immediate.
#IBAction func StartButton(sender: AnyObject) {
var pageArray: PageArray = PageArray()
for quote in quoteList {
var newPage = Page(nibName: "Page", bundle: nil)
let _ = newPage.view // A trick. It's help your view load immediate
// Your Page has been loaded.
newPage.Label.text = quote
pageArray.append(newPage)
}

Swift - How do I update a label the Relative altitude change in iOS

I have managed to get this to print the Relative Altitude data to the log however what I would like to do is get it to print to a designated label.Any help would be appreciated.
import UIKit
import CoreMotion
class ViewController: UIViewController {
#IBOutlet weak var altitudeLabel: UILabel!
let altimeter = CMAltimeter()
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.
}
#IBAction func start(sender: AnyObject) {
if CMAltimeter.isRelativeAltitudeAvailable() {
altimeter.startRelativeAltitudeUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: { data, error in
if (error == nil) {
println("relative Altitude: \(data.relativeAltitude)")
println("Pressure: \(data.pressure)")
}
})
}
}
}
You can use the following line to assign a float value with 2 decimal places to your UILabel outlet:
self.altitudeLabel.text = String(format: "%0.2f", data.relativeAltitude)
I ended up using this and it will due for now:
var myIntValue:Int = Int(data.relativeAltitude)
println ("My value is \(myIntValue)")
self.altitudeLabel.text = ("\(myIntValue) M")

Swift If Statement Not Working with UILabel

My if statement is not displaying what I want it to. Can anyone help? I want to display some text in a UILabel that will be decided from weather the random number is below or above 50.
Here is the code. The IF Statement is at the end.
import UIKit
import AVFoundation
class ViewController: UIViewController {
var pianoSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("two_tone_nav", ofType: "mp3")!)
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
audioPlayer = AVAudioPlayer(contentsOfURL: pianoSound, error: nil)
audioPlayer.prepareToPlay()
// 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.
}
#IBOutlet weak var Number: UILabel!
#IBOutlet weak var BA50: UILabel!
#IBAction func Generate(sender: AnyObject) {
audioPlayer.play()
var Generate = Int(arc4random_uniform(100))
Number.text = String(Generate)
func AboveBelow50(){
if Generate>=50 {
self.BA50.text = "No"
}
else {
self.BA50.text = "Yes"
}
}
}
}
Put your function:
func AboveBelow50(Generate: Int){
if Generate>=50 {
self.BA50.text = "No"
} else {
self.BA50.text = "Yes"
}
Out side your IBAction, and change it this way.
And call inside your IBAction:
var Generate = Int(arc4random_uniform(100))
AboveBelow50(Generate)

Resources