简体   繁体   中英

getting data from one view controller to another

I am getting the battery level of my bluetooth le device (batteryLevel) which is a float in one view. I want to pass it to another view to display it in a textfield.

code in view one

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:    
    (CBCharacteristic *)characteristic error:(NSError *)error
    {[self.testPeripheral readValueForCharacteristic:mycharacteristic];

    char batlevel;
    [characteristic.value getBytes:&batlevel length:1];
    self.batteryLevel = (float)batlevel;

    NSLog(@"level;%f",batteryLevel);}

this gives me a value like 80.00000

I want to put this into another view to display.

I have tried in view2.h file I have placed

view1 *t

and then

- (void) batteryIndicatorTimer:(NSTimer *)timer {
    TIBLEUIBatteryBar.progress = t.batteryLevel / 100;
    [t readBattery:[t testPeripheral]];               // Read battery value of keyfob again
    NSLog(@"t.batterylevel:%f",t.batteryLevel);
}

but I don't get a value for t.batteryLevel

what am I doing wrong and how can I do this?

There's a myriad number of ways to accomplish this using delegates or assigning properties in presentingViewControllers/destinationViewControllers, but since I don't know your app flow I'll give you a way that should work with whatever setup you have. Just update batteryLevel in your viewController that is the peripheralDelegate then simply save the value to the NSUserDefaults:

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:
 (CBCharacteristic *)characteristic error:(NSError *)error
 {
   //Grab your battery value and store in float
   //Then just save to defaults so you can access wherever.. Keep overwriting this value each time you update

   [[NSUserDefaults standardUserDefaults]setFloat:batteryVal forKey:@"battery_level"];

 }

And then inside your other viewController just assign the value inside viewWillAppear or something.

-(void)viewWillAppear:(BOOL)animated
{
    float batteryLevel = [[NSUserDefaults standardUserDefaults]floatForKey:@"battery_level"];
    self.yourTextField.text = [NSString stringWithFormat:@"%f",batteryLevel];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM