Skip to content

Commit ca7aab8

Browse files
jung hyun kojung hyun ko
jung hyun ko
authored and
jung hyun ko
committed
swift test
1 parent 68ce2cb commit ca7aab8

File tree

7 files changed

+71
-313
lines changed

7 files changed

+71
-313
lines changed

LICENSE

+21-1
Original file line numberDiff line numberDiff line change
@@ -1 +1,21 @@
1-
TODO: Add your license here.
1+
MIT License
2+
3+
Copyright (c) 2021 jung hyun, ko
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

example/lib/main.dart

+17-36
Original file line numberDiff line numberDiff line change
@@ -1,75 +1,56 @@
11
//A Flutter app that depends on the plugin, and illustrates how to use it.
22
import 'package:flutter/material.dart';
33
import 'dart:async';
4-
5-
//import 'package:flutter/services.dart';
64
import 'package:proximity_sensor/proximity_sensor.dart';
75

6+
////////////////////////////////////////////////////////////////////////////////
7+
////////////////////////////////////////////////////////////////////////////////
88
void main() {
99
runApp(MyApp());
1010
}
1111

12+
////////////////////////////////////////////////////////////////////////////////
1213
class MyApp extends StatefulWidget {
1314
@override
1415
_MyAppState createState() => _MyAppState();
1516
}
1617

18+
////////////////////////////////////////////////////////////////////////////////
1719
class _MyAppState extends State<MyApp> {
18-
//String _platformVersion = 'Unknown';
19-
List<StreamSubscription<dynamic>> _streamSubscriptions =
20-
<StreamSubscription<dynamic>>[];
21-
22-
bool _proximityOn = false;
20+
bool _isNear = false;
21+
StreamSubscription<dynamic> _streamSubscription;
2322

2423
@override
2524
void initState() {
2625
super.initState();
2726
initPlatformState();
2827
}
2928

29+
@override
30+
void dispose() {
31+
super.dispose();
32+
_streamSubscription.cancel();
33+
}
34+
3035
// Platform messages are asynchronous, so we initialize in an async method.
3136
Future<void> initPlatformState() async {
32-
//TODO null check. --> ProximitySensor.proximityEvents
33-
_streamSubscriptions
34-
.add(ProximitySensor.proximityEvents.listen((ProximityEvent event) {
37+
_streamSubscription = ProximitySensor.proximityEvents.listen((int event) {
3538
setState(() {
36-
_proximityOn = event.getValue();
37-
print("in main.dart : " + _proximityOn.toString());
39+
_isNear = (event == 0) ? false : true;
40+
//print("in main.dart : " + _isNear.toString());
3841
});
39-
}));
40-
41-
/*
42-
//String platformVersion;
43-
bool proximityOn = false;
44-
// Platform messages may fail, so we use a try/catch PlatformException.
45-
try {
46-
//platformVersion = await ProximitySensor.platformVersion;
47-
//proximityOn = await ProximitySensor.proximityOn;
48-
} on PlatformException {
49-
//TODO
50-
}
51-
52-
// If the widget was removed from the tree while the asynchronous platform
53-
// message was in flight, we want to discard the reply rather than calling
54-
// setState to update our non-existent appearance.
55-
if (!mounted) return;
56-
57-
setState(() {
58-
//_platformVersion = platformVersion;
59-
_proximityOn = proximityOn;
6042
});
61-
*/
6243
}
6344

6445
@override
6546
Widget build(BuildContext context) {
6647
return MaterialApp(
6748
home: Scaffold(
6849
appBar: AppBar(
69-
title: const Text('Proximity Sensor example'),
50+
title: const Text('Proximity Sensor Example'),
7051
),
7152
body: Center(
72-
child: Text('proximity : $_proximityOn\n'),
53+
child: Text('proximity sensor, is near ? $_isNear\n'),
7354
),
7455
),
7556
);

ios/Classes/ProximitySensorPlugin.m

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
#import "proximity_sensor-Swift.h"
1111
#endif
1212

13-
////////////////////////////////////////////////////////////////////////////////
13+
//==============================================================================
1414
@implementation ProximitySensorPlugin
1515
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
1616
[SwiftProximitySensorPlugin registerWithRegistrar:registrar];
+25-68
Original file line numberDiff line numberDiff line change
@@ -1,92 +1,49 @@
11
import Flutter
22
import UIKit
33

4-
//https://flutterdevs.com/blog/creating-a-flutter-plugin-for-android-and-ios-image-gallery/
5-
4+
//==============================================================================
65
public class SwiftProximityStreamHandler : NSObject,FlutterStreamHandler
76
{
7+
let notiCenter = NotificationCenter.default
8+
let device = UIDevice.current
9+
var observer: NSObjectProtocol?
10+
811
public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
9-
let device = UIDevice.current
1012
device.isProximityMonitoringEnabled = true
11-
//NotificationCenter.default.addObserver(forName: <#T##NSNotification.Name?#>, object: <#T##Any?#>, queue: <#T##OperationQueue?#>, using: <#T##(Notification) -> Void#>)
12-
NotificationCenter.default.addObserver(forName: UIDevice.proximityStateDidChangeNotification, object: device, queue: nil)
13-
{ /* [weak self] */ (notification) in
14-
//guard let strongSelf = self else { return }
15-
if let device = notification.object as? UIDevice {
16-
print("from swift ...")
17-
// Int32 type 인 경우 dart 에서 수신하는 것은 4 byte: this is dart code --> [0, 0, 0, 0]
18-
// --> dart 에서 처리시 list 로! 즉, return new ProximityEvent(event.cast<int>()[0]);
19-
// Int8 type 인 경우 dart 에서 수신하는 것은 1 byte: this is dart code --> [0]
20-
// --> 이경우에는 dart 코드에서는 리스트로 처리 안해도 됨 !
21-
// return new ProximityEvent(event.cast<int>());
22-
let onoff:Int8 = device.proximityState ? 0 : 1
23-
print(onoff)
24-
var data = Data()
25-
withUnsafeBytes(of: onoff) {buffer in data.append(buffer.bindMemory(to: Int8.self))}
26-
events(data)
27-
}
28-
}
29-
////////////////
30-
/*
31-
NotificationCenter.default.addObserver(self, selector: #selector(proximityStateDidChange),
32-
name: UIDevice.proximityStateDidChangeNotification,
33-
object: device)
34-
*/
13+
14+
observer = notiCenter.addObserver(forName: UIDevice.proximityStateDidChangeNotification,
15+
object: device,
16+
queue: nil,
17+
using : { (notification) in
18+
if let device = notification.object as? UIDevice {
19+
let onoff:Int8 = device.proximityState ? 1 : 0
20+
var data = Data()
21+
withUnsafeBytes(of: onoff) {
22+
buffer in data.append(buffer.bindMemory(to: Int8.self))}
23+
24+
events(data)
25+
}
26+
})
3527
return nil
3628
}
3729

3830
public func onCancel(withArguments arguments: Any?) -> FlutterError? {
39-
//TODO
31+
notiCenter.removeObserver(self, name: UIDevice.proximityStateDidChangeNotification, object: nil)
32+
device.isProximityMonitoringEnabled = false
33+
4034
return nil
4135
}
42-
/*
43-
@objc func proximityStateDidChange(notification: Notification)
44-
{
45-
if let device = notification.object as? UIDevice {
46-
print("from swift ...")
47-
print( device)
48-
}
49-
}
50-
*/
5136
}
5237

38+
//==============================================================================
5339
public class SwiftProximitySensorPlugin: NSObject, FlutterPlugin
5440
{
55-
//static var observer:NotificationCenter = NotificationCenter.default
5641
static var stream_handler:SwiftProximityStreamHandler = SwiftProximityStreamHandler()
5742
static var channel:FlutterEventChannel = FlutterEventChannel()
5843

59-
public static func register(with registrar: FlutterPluginRegistrar)
60-
{
61-
//---------------------------- FlutterEventChannel
44+
public static func register(with registrar: FlutterPluginRegistrar) {
6245
let channel = FlutterEventChannel.init(name: "proximity_sensor", binaryMessenger: registrar.messenger())
6346
channel.setStreamHandler(stream_handler)
64-
//----------------------------
65-
//auto generated code ...!
66-
/*
67-
let channel = FlutterMethodChannel(name: "proximity_sensor", binaryMessenger: registrar.messenger())
68-
let instance = SwiftProximitySensorPlugin()
69-
registrar.addMethodCallDelegate(instance, channel: channel)
70-
*/
71-
}
72-
73-
/*
74-
public func detachFromEngine(for registrar: FlutterPluginRegistrar) {
75-
let device = UIDevice.current
76-
device.isProximityMonitoringEnabled = false
77-
NotificationCenter.default.removeObserver(observer)
78-
}
79-
*/
80-
//////////////////////////////////////////////////////////////////////////////
81-
// - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result;
82-
// Called if this plugin has been registered to receive `FlutterMethodCall`s.
83-
// @param call The method call command object.
84-
// @param result A callback for submitting the result of the call.
85-
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
86-
NSLog(call.method) //"listen"
87-
if call.method == "listen" {
88-
}
89-
//result("iOS " + UIDevice.current.systemVersion)
90-
}
47+
}
9148
}
9249

lib/proximity_sensor.dart

+5-66
Original file line numberDiff line numberDiff line change
@@ -3,73 +3,12 @@
33
import 'dart:async';
44
import 'package:flutter/services.dart';
55

6-
////////////////////////////////////////////////////////////////////////////////
7-
//XXX stream 을 받게 추가한것
8-
const EventChannel _stream_channel = EventChannel('proximity_sensor');
9-
10-
class ProximityEvent {
11-
final int onoff;
12-
ProximityEvent(this.onoff);
13-
bool getValue() => onoff == 0 ? true : false;
14-
15-
@override
16-
String toString() => onoff == 0 ? 'true' : 'false';
17-
}
18-
19-
/*
20-
ProximityEvent _listToProximityEvent(int onoff) {
21-
return new ProximityEvent(onoff);
22-
}
23-
*/
24-
25-
/*
26-
Stream<ProximityEvent> get proximityEvents {
27-
_sensor_events = _stream_channel
28-
.receiveBroadcastStream()
29-
//.map((event) => _listToProximityEvent(event.cast<int>()));
30-
.map((event) => new ProximityEvent(event.cast<int>()));
31-
return _sensor_events;
32-
}
33-
*/
34-
356
////////////////////////////////////////////////////////////////////////////////
367
class ProximitySensor {
37-
static Stream<ProximityEvent> _sensor_events;
38-
static Stream<ProximityEvent> get proximityEvents {
39-
_sensor_events = _stream_channel.receiveBroadcastStream()
40-
//.map((event) => _listToProximityEvent(event.cast<int>()));
41-
//.map((event) => new ProximityEvent(event.cast<int>()));
42-
.map((event) {
43-
print("this is dart code --> " + event.toString());
44-
//return new ProximityEvent(event.cast<int>()[0]); //XXX android 에서는 몇바이트로 넘겨주는지 확인해야.
45-
46-
return new ProximityEvent(event.cast<int>()); // 1 byte 를 넘겨주는 경우에 가능.
47-
//--> list<int,int..>
48-
//XXX XXX XXX error 안됨. list 임.!
49-
//--> Unhandled Exception: type 'CastList<int, int>' is not a subtype of type 'int'
50-
}); //XXX TEST
51-
52-
//print(_sensor_events.toString()); //TEST --> 실행안됨
53-
/*
54-
print("return events...");
55-
print("this is dart code --> " + _sensor_events.toString());
56-
*/
57-
return _sensor_events; //null error 방지 _stream_channel.receiveBroadcastStream() 로 만들어진것을 보내지 않으면 에러 발생
58-
}
59-
/*
60-
//XXX 이게 원래 있던것
61-
//static const MethodChannel _channel = const MethodChannel('proximity_sensor');
62-
63-
// static Future<String> get platformVersion async {
64-
// final String version = await _channel.invokeMethod('getPlatformVersion');
65-
// return version;
66-
// }
67-
68-
static Future<bool> get proximityOn async {
69-
// final String version = await _channel.invokeMethod('getPlatformVersion');
70-
// return version;
71-
final bool onoff = await _channel.invokeMethod('getProximityOnOff');
72-
return onoff;
8+
static EventChannel _streamChannel = EventChannel('proximity_sensor');
9+
static Stream<int> get proximityEvents {
10+
return _streamChannel.receiveBroadcastStream().map((event) {
11+
return event.cast<int>()[0];
12+
});
7313
}
74-
*/
7514
}

0 commit comments

Comments
 (0)