Skip to content

Commit

Permalink
Update send message function
Browse files Browse the repository at this point in the history
  • Loading branch information
vietdq2701 committed Sep 16, 2020
1 parent 2089deb commit c260999
Show file tree
Hide file tree
Showing 8 changed files with 206 additions and 139 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 0.0.3

* Update send message function

## 0.0.2

* fix static analysis.
Expand Down
2 changes: 2 additions & 0 deletions example/ios/Runner.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -257,13 +257,15 @@
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh",
"${PODS_ROOT}/../Flutter/Flutter.framework",
"${BUILT_PRODUCTS_DIR}/SwiftyJSON/SwiftyJSON.framework",
"${BUILT_PRODUCTS_DIR}/Toast/Toast.framework",
"${BUILT_PRODUCTS_DIR}/flutter_nearby_connections/flutter_nearby_connections.framework",
"${BUILT_PRODUCTS_DIR}/fluttertoast/fluttertoast.framework",
);
name = "[CP] Embed Pods Frameworks";
outputPaths = (
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Flutter.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SwiftyJSON.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Toast.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/flutter_nearby_connections.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/fluttertoast.framework",
);
Expand Down
11 changes: 5 additions & 6 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_nearby_connections/flutter_nearby_connections.dart';
import 'package:fluttertoast/fluttertoast.dart';
Expand Down Expand Up @@ -112,10 +113,8 @@ class _DevicesListScreenState extends State<DevicesListScreen> {
});
});

receivedDataSubscription =
nearbyService.dataReceivedSubscription(callback: (data) {
Fluttertoast.showToast(
msg: "Device ID: ${data.deviceID} , message: ${data.message}");
receivedDataSubscription = nearbyService.dataReceivedSubscription(callback: (data) {
Fluttertoast.showToast(msg: jsonEncode(data));
});

if (widget.deviceType == DeviceType.browser) {
Expand Down Expand Up @@ -265,8 +264,8 @@ class _DevicesListScreenState extends State<DevicesListScreen> {
FlatButton(
child: Text("Send"),
onPressed: () {
nearbyService.sendMessage(
device.deviceID, myController.text);
String jsonData = '{ "message": \" ${myController.text}\" }';
nearbyService.sendMessage(device.deviceID, jsonDecode(jsonData));
myController.text = '';
},
)
Expand Down
7 changes: 2 additions & 5 deletions ios/Classes/Device.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Foundation
import MultipeerConnectivity

import SwiftyJSON
class Device: NSObject {
let peerID: MCPeerID
var session: MCSession?
Expand Down Expand Up @@ -43,10 +43,7 @@ extension Device: MCSessionDelegate {
}

public func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
if let message = try? JSONDecoder().decode(Message.self, from: data) {
self.lastMessageReceived = message
NotificationCenter.default.post(name: Device.messageReceivedNotification, object: nil, userInfo: ["from": peerID])
}
NotificationCenter.default.post(name: Device.messageReceivedNotification, object: nil, userInfo: ["from": peerID, "data": data])
}

public func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) { }
Expand Down
66 changes: 63 additions & 3 deletions ios/Classes/Message.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,75 @@
//

import Foundation
import SwiftyJSON

struct Message: Codable {
let body: String
}

extension Device {
func send(text: String) throws {
let message = Message(body: text)
let payload = try JSONEncoder().encode(message)
try self.session?.send(payload, toPeers: [self.peerID], with: .reliable)
try self.session?.send(text.data(using: .utf8) ?? Data(), toPeers: [self.peerID], with: .reliable)
}

func send(json: JSON) throws {
try self.session?.send(json.rawData(), toPeers: [self.peerID], with: .reliable)
}

func send(data: Data) throws {
try self.session?.send(data, toPeers: [self.peerID], with: .reliable)
}
}

struct ReceivedResponse {
var deviceID: String?
var message: MessageReponse

init(json: JSON) {
deviceID = json["deviceID"].string
message = MessageReponse(json: json["message"])
}
}

struct MessageReponse {
var items: [MessageResponseItem] = []
var subTotal: NSNumber?
var rounding: NSNumber?
var total: NSNumber?

init(json: JSON) {
items = json["items"].array?.compactMap({return MessageResponseItem(json: $0)}) ?? []
subTotal = json["subTotal"].number
rounding = json["rounding"].number
total = json["total"].number
}
}

struct MessageResponseItem {
var quantity: NSNumber?
var itemCollection: MessageItemCollection?

init(json: JSON) {
quantity = json["quantity"].number
itemCollection = MessageItemCollection(json: json["itemCollection"])
}
}

struct MessageItemCollection {
var name: String?
var status: MessageItemCollectionStatus?
var imageUrl: String?
var price: NSNumber?

init(json: JSON) {
name = json["name"].string
status = MessageItemCollectionStatus(rawValue: json["status"].stringValue)
imageUrl = json["imageUrl"].string
price = json["price"].number
}
}

enum MessageItemCollectionStatus: String {
case active = "ACTIVE"
}

212 changes: 104 additions & 108 deletions ios/Classes/SwiftFlutterNearbyConnectionsPlugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,120 +11,116 @@ enum MethodCall: String {
case initNearbyService = "init_nearby_service"
case startAdvertisingPeer = "start_advertising_peer"
case startBrowsingForPeers = "start_browsing_for_peers"

case stopAdvertisingPeer = "stop_advertising_peer"
case stopBrowsingForPeers = "stop_browsing_for_peers"

case invitePeer = "invite_peer"
case disconnectPeer = "disconnect_peer"

case sendMessage = "send_message"
}

public class SwiftFlutterNearbyConnectionsPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "flutter_nearby_connections", binaryMessenger: registrar.messenger())
let instance = SwiftFlutterNearbyConnectionsPlugin(channel: channel)
registrar.addMethodCallDelegate(instance, channel: channel)
}

var currentReceivedDevice: Device? = Device(peerID: MPCManager.instance.localPeerID)

let channel: FlutterMethodChannel

struct DeviceJson {
var deviceID:String
var displayName:String
var state:Int

func toStringAnyObject() -> [String: Any] {
return [
"deviceID": deviceID,
"displayName": displayName,
"state": state
]
}
}

struct MessageJson {
var deviceID:String
var message:String
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "flutter_nearby_connections", binaryMessenger: registrar.messenger())
let instance = SwiftFlutterNearbyConnectionsPlugin(channel: channel)
registrar.addMethodCallDelegate(instance, channel: channel)
}

var currentReceivedDevice: Device? = Device(peerID: MPCManager.instance.localPeerID)

let channel: FlutterMethodChannel

struct DeviceJson {
var deviceID:String
var displayName:String
var state:Int

func toStringAnyObject() -> [String: Any] {
return [
"deviceID": deviceID,
"displayName": displayName,
"state": state
]
}
}

struct MessageJson {
var deviceID:String
var message:String

func toStringAnyObject() -> [String: Any] {
return [
"deviceID": deviceID,
"message": message
]
}
}

@objc func stateChanged(){
let devices = MPCManager.instance.devices.compactMap({return DeviceJson(deviceID: $0.deviceId, displayName: $0.peerID.displayName, state: $0.state.rawValue)})
channel.invokeMethod(INVOKE_CHANGE_STATE_METHOD, arguments: JSON(devices.compactMap({return $0.toStringAnyObject()})).rawString())
}

@objc func messageReceived(notification: Notification) {
do {
if let data = notification.userInfo?["data"] as? Data, let stringData = JSON(data).rawString() {
self.channel.invokeMethod(INVOKE_MESSAGE_RECEIVE_METHOD,
arguments: stringData)
}
} catch let e {
print(e.localizedDescription)
}
}

public init(channel:FlutterMethodChannel) {
self.channel = channel
super.init()

NotificationCenter.default.addObserver(self, selector: #selector(stateChanged), name: MPCManager.Notifications.deviceDidChangeState, object: nil)

NotificationCenter.default.addObserver(self, selector: #selector(messageReceived), name: Device.messageReceivedNotification, object: nil)

MPCManager.instance.deviceDidChange = {[weak self] in
self?.stateChanged()
}
}

public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch MethodCall(rawValue: call.method) {
case .initNearbyService:
let serviceType:String = call.arguments as? String ?? SERVICE_TYPE
MPCManager.instance.setup(serviceType: serviceType)
case .startAdvertisingPeer:
MPCManager.instance.startAdvertisingPeer()
case .startBrowsingForPeers:
MPCManager.instance.startBrowsingForPeers()
case .stopAdvertisingPeer:
MPCManager.instance.stopAdvertisingPeer()
case .stopBrowsingForPeers:
MPCManager.instance.stopBrowsingForPeers()
case .invitePeer:
let deviceID:String? = call.arguments as? String ?? nil
if(deviceID != nil){
MPCManager.instance.invitePeer(deviceID: deviceID!)
}
case .disconnectPeer:
let deviceID:String? = call.arguments as? String ?? nil
if(deviceID != nil){
MPCManager.instance.disconnectPeer(deviceID: deviceID!)
}
case .sendMessage:
guard let jsonData = call.arguments as? String, let data = jsonData.data(using: String.Encoding.utf8) else {fatalError()}
do {
let json = JSON(data)
if let device = MPCManager.instance.device(for: json["device_id"].stringValue) {
currentReceivedDevice = device
try device.send(data: data)
}
} catch let error as NSError {
print(error)
}
}

func toStringAnyObject() -> [String: Any] {
return [
"deviceID": deviceID,
"message": message
]
}
}

@objc func stateChanged(){
let devices = MPCManager.instance.devices.compactMap({return DeviceJson(deviceID: $0.deviceId, displayName: $0.peerID.displayName, state: $0.state.rawValue)})
channel.invokeMethod(INVOKE_CHANGE_STATE_METHOD, arguments: JSON(devices.compactMap({return $0.toStringAnyObject()})).rawString())
}

@objc func messageReceived(notification: Notification) {
if let formDevice = notification.userInfo?["from"] as? MCPeerID, let device = MPCManager.instance.devices.first(where: {return $0.peerID == formDevice}) {
let message = MessageJson(deviceID: device.deviceId, message: device.lastMessageReceived?.body ?? "")
channel.invokeMethod(INVOKE_MESSAGE_RECEIVE_METHOD,
arguments: JSON(message.toStringAnyObject()).rawString())
}
}

public init(channel:FlutterMethodChannel) {
self.channel = channel
super.init()

NotificationCenter.default.addObserver(self, selector: #selector(stateChanged), name: MPCManager.Notifications.deviceDidChangeState, object: nil)

NotificationCenter.default.addObserver(self, selector: #selector(messageReceived), name: Device.messageReceivedNotification, object: nil)

MPCManager.instance.deviceDidChange = {[weak self] in
self?.stateChanged()
}
}

public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch MethodCall(rawValue: call.method) {
case .initNearbyService:
let serviceType:String = call.arguments as? String ?? SERVICE_TYPE
MPCManager.instance.setup(serviceType: serviceType)
case .startAdvertisingPeer:
MPCManager.instance.startAdvertisingPeer()
case .startBrowsingForPeers:
MPCManager.instance.startBrowsingForPeers()
case .stopAdvertisingPeer:
MPCManager.instance.stopAdvertisingPeer()
case .stopBrowsingForPeers:
MPCManager.instance.stopBrowsingForPeers()
case .invitePeer:
let deviceID:String? = call.arguments as? String ?? nil
if(deviceID != nil){
MPCManager.instance.invitePeer(deviceID: deviceID!)
}
case .disconnectPeer:
let deviceID:String? = call.arguments as? String ?? nil
if(deviceID != nil){
MPCManager.instance.disconnectPeer(deviceID: deviceID!)
}
case .sendMessage:
let jsonData: String? = call.arguments as? String ?? nil
if(jsonData != nil){
var dictonary:NSDictionary?
if let data = jsonData!.data(using: String.Encoding.utf8) {
do {
dictonary = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] as NSDictionary?
if dictonary != nil, let device = MPCManager.instance.device(for: dictonary?["deviceID"] as? String ?? "") {
currentReceivedDevice = device
try device.send(text: dictonary?["message"] as? String ?? "")
}
} catch let error as NSError {
print(error)
}
}
}
default:
break
}
}
}
}
Loading

0 comments on commit c260999

Please sign in to comment.