I'm new to swift and iOS. I'm working on an app for a highschool project. I have two files, each with a class defined in them. ViewController with a class of the same name, and BLEHandler, with one class BLEManager and another BLEHandler.
BLEHandler goes out and scans for advertising BLE devices and collects the UUIDs of those devices and prints them out. For now, I'm substituting "variable" for that UUID
.
I want to be able to print the value of "variable" to the console when you press a button (which is set up in ViewController). This means that I need to have the "variable"s value from BLEHandler
accessible in ViewController
.
My current code to set up "variable" in the userdefaults is given here.
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("test", forKey: "variable")
And my code to access "variable" from ViewController
is given here:
@IBAction func buttonPress(sender: AnyObject) {
let defaults = NSUserDefaults.standardUserDefaults()
let name = defaults.stringForKey("variable")
println(name)
}
It seems like it should work, but all I get from the println(name)
line is nil
...
Any suggestions?
Thanks in advance!
EDIT: Here is the full code as it currently stands:
VIEWCONTROLLER CLASS:
import UIKit
import Foundation
import CoreBluetooth
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func buttonPress(sender: AnyObject) {
let defaults = NSUserDefaults.standardUserDefaults()
let name = defaults.stringForKey("variable")
println(name)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
BLEHANDLER CLASS:
import Foundation
import CoreBluetooth
class BLEManager{
var centralManager: CBCentralManager!
var bleHandler: BLEHandler
init(){
self.bleHandler=BLEHandler()
self.centralManager=CBCentralManager(delegate:self.bleHandler, queue:nil)
}
}
class BLEHandler: NSObject, CBCentralManagerDelegate{
override init(){
super.init()
}
func centralManagerDidUpdateState(central: CBCentralManager!){
switch(central.state){
case .Unsupported:
println("not supported")
case .Unauthorized:
println("not authorized")
case .Unknown:
println("ble unknown")
case .Resetting:
println("resetting")
case .PoweredOff:
println("powered off")
case .PoweredOn:
println("powered on")
central.scanForPeripheralsWithServices(nil, options: nil)
default:
println("ble default")
}
}
func centralManager(central: CBCentralManager!, didDiscoverPeripheral peripheral: CBPeripheral!, advertisementData: [NSObject:AnyObject]!,RSSI:NSNumber!)
{
central.connectPeripheral(peripheral, options: nil)
var pName=peripheral.name
println("\(pName):\(RSSI) dbm")
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("test", forKey: "variable")
}
}