1
0
mirror of https://github.com/flutter/samples.git synced 2026-03-30 08:11:40 +00:00

Simplify experimental pedometer example (#2104)

Since ffigen added support for
[`NativeCallable.listener`](https://api.flutter.dev/flutter/dart-ffi/NativeCallable/NativeCallable.listener.html)
to its ObjC bindings, this example can be simplified. We can replace the
`Dart_Port` logic with `ObjCBlock.listener`, which lets us get rid of
most of the native code.

We still need a small bit of native code to `retain` a reference to the
callback's arguments before invoking the listener, otherwise the
arguments may be ref counted and deleted before the Dart side of the
callback is invoked. See https://github.com/dart-lang/native/issues/835
This commit is contained in:
Liam Appelbe
2023-12-06 00:58:58 -08:00
committed by GitHub
parent e598d6a771
commit f0e6da6d24
5 changed files with 27861 additions and 21805 deletions

View File

@@ -1,15 +1,7 @@
#import <CoreMotion/CoreMotion.h>
#import <CoreMotion/CMPedometer.h>
#import <Foundation/Foundation.h>
#import <Foundation/NSDate.h>
#include "dart-sdk/include/dart_api_dl.h"
@interface PedometerHelper : NSObject
+ (void) startPedometerWithPort: (Dart_Port) sendPort
pedometer: (CMPedometer*) pedometer
start: (NSDate*) start
end: (NSDate*) end;
@end
// TODO(https://github.com/dart-lang/native/issues/835): Generate this wrapper
// automatically.
CMPedometerHandler wrapCallback(CMPedometerHandler callback);

View File

@@ -2,37 +2,11 @@
#import <CoreMotion/CoreMotion.h>
#import <CoreMotion/CMPedometer.h>
#import <Foundation/Foundation.h>
#import <Foundation/NSDate.h>
#include "dart-sdk/include/dart_api_dl.h"
// Need to import the dart headers to get the definitions Dart_CObject
#include "dart-sdk/include/dart_api_dl.h"
// Helper function that takes a pointer to CMPedometer data and converts it to a Dart C Object
static Dart_CObject NSObjectToCObject(CMPedometerData* n) {
Dart_CObject cobj;
cobj.type = Dart_CObject_kInt64;
cobj.value.as_int64 = (int64_t) n;
return cobj;
// TODO(https://github.com/dart-lang/native/issues/835): Generate this wrapper
// automatically.
CMPedometerHandler wrapCallback(CMPedometerHandler callback) {
return [^(CMPedometerData *data, NSError *error) {
return callback([data retain], [error retain]);
} copy];
}
@implementation PedometerHelper
+(void)startPedometerWithPort: (Dart_Port) sendPort pedometer: (CMPedometer*) pedometer start: (NSDate*) start end: (NSDate*) end {
// Start the pedometer
[pedometer queryPedometerDataFromDate:start toDate:end withHandler:^(CMPedometerData *pedometerData, NSError *error) {
if(error == nil){
pedometerData = [pedometerData retain];
Dart_CObject data = NSObjectToCObject(pedometerData);
const bool success = Dart_PostCObject_DL(sendPort, &data);
NSAssert(success, @"Couldn't send to Dart@");
}
else{
NSLog(@"Error:%@", error);
}
}];
}
@end