IOS swift Web Socket SRWebSocket set response timeout - ios

I am using SRWebSocket/SocketRocket library in my app I am unable to set response timeout for it . I want to show a message if socket does not receive any data after few seconds
Following is my code
socketRocket = SRWebSocket(url: URL(string: streamUrl)!)
socketRocket?.delegate = self
socketRocket?.open()
Using following callback methods as well
func webSocketDidOpen(_ webSocket: SRWebSocket!) {
print("webSocketDidOpen")
showTableView()
}
func webSocket(_ webSocket: SRWebSocket!, didCloseWithCode code: Int, reason: String!, wasClean: Bool) {
getConversationId()
}
func webSocket(_ webSocket: SRWebSocket!, didFailWithError error: Error!) {
print("didFailWithError\(error)")
showLErrorView()
}
func webSocket(_ webSocket: SRWebSocket!, didReceiveMessage message: Any!) {
}
here is link to library
https://github.com/facebook/SocketRocket

If you want to display some message when you don't get a response you can use a Timer, the basics it looks like that:
var timer: Timer?
var responseTimeout: TimeInterval = 15
func startTimer() {
timer?.invalidate()
timer = Timer.scheduledTimer(withTimeInterval: responseTimeout, repeats: false, block: {[weak self] timer in
self?.onResponseTimeout()
})
}
func onResponseTimeout() {
print("Didn't get response")
}
func webSocket(_ webSocket: SRWebSocket!, didReceiveMessage message: Any!) {
print(message)
timer?.invalidate() //invalidate timer when you get a message
}
and then you can call startTimer() when it is needed i.e. when the socket is opened:
func webSocketDidOpen(_ webSocket: SRWebSocket!) {
print("webSocketDidOpen")
showTableView()
startTimer()
}
or after you send a message:
socketRocket?.send(message)
startTimer()
If you also want to set a timeout for connection (it is something separate from resopone timout), you can use URLRequest instead of URL:
let request = URLRequest(url: url, timeoutInterval: 30) //it is 30 sec connection timeout
socketRocket = SRWebSocket(urlRequest: request)
socketRocket?.delegate = self
socketRocket?.open()
Full class that supports both connection and response timeout:
import Foundation
import SocketRocket
class WebSocket: NSObject, SRWebSocketDelegate {
var socketRocket: SRWebSocket?
var timer: Timer?
var responseTimeout: TimeInterval = 15
func open(url: URL, connectionTimeout: TimeInterval = 10) {
let request = URLRequest(url: url, timeoutInterval: connectionTimeout)
socketRocket = SRWebSocket(urlRequest: request)
socketRocket?.delegate = self
socketRocket?.open()
}
func send(message: String) {
socketRocket?.send(message)
startTimer()
}
func startTimer() {
timer?.invalidate()
timer = Timer.scheduledTimer(withTimeInterval: responseTimeout, repeats: false, block: {[weak self] timer in
self?.onResponseTimeout()
})
}
func onResponseTimeout() {
print("Didn't get response")
}
func webSocketDidOpen(_ webSocket: SRWebSocket!) {
print("webSocketDidOpen")
startTimer()
}
func webSocket(_ webSocket: SRWebSocket!, didCloseWithCode code: Int, reason: String!, wasClean: Bool) {
print("closed with code: \(code), reason: \(reason), wasClean: \(wasClean)")
timer?.invalidate()
}
func webSocket(_ webSocket: SRWebSocket!, didFailWithError error: Error!) {
print("didFailWithError\(error)")
timer?.invalidate()
}
func webSocket(_ webSocket: SRWebSocket!, didReceiveMessage message: Any!) {
print(message)
timer?.invalidate()
}
}

Related

How do I run a function in the background on watchOS and iOS?

I'm trying to run a function in the background on iOS and watchOS, and I found a code sample, but it didn't work for me.
I tried some sample code that I found on GitHub, and a dispatch thread function.
..........
private func startWorkout() {
let workoutConfiguration = HKWorkoutConfiguration()
workoutConfiguration.activityType = .other
do {
workoutSession = try HKWorkoutSession(healthStore: healthStore, configuration: workoutConfiguration)
workoutSession?.delegate = self
// HKWorkoutSession.startActivity(workoutSession!)
healthStore.start(workoutSession!)
} catch {
print(error)
}
}
#objc fileprivate func vibrate() {
WKInterfaceDevice.current().play(.success)
}
........
extension InterfaceController: HKWorkoutSessionDelegate {
func workoutSession(_ workoutSession: HKWorkoutSession, didFailWithError error: Error) {
}
func workoutSession(_ workoutSession: HKWorkoutSession, didGenerate event: HKWorkoutEvent) {
}
func workoutSession(_ workoutSession: HKWorkoutSession, didChangeTo toState: HKWorkoutSessionState, from fromState: HKWorkoutSessionState, date: Date) {
switch toState {
case .running:
hapticFeedbackTimer = Timer(timeInterval: 0, target: self, selector: #selector(vibrate), userInfo: nil, repeats: true)
RunLoop.main.add(hapticFeedbackTimer!, forMode: .default)
default:
hapticFeedbackTimer?.invalidate()
hapticFeedbackTimer = nil
}
}
}```
I expected the function vibrate to be run in the background, but instead, nothing happened
to use the background thread you can use this extension:
extension DispatchQueue {
static func backgroundQueue(_ backgroundOperations: ( () -> Void )? = nil, completion: (() -> Void)? = nil) {
DispatchQueue.global(qos: .background).async {
backgroundOperations?()
if let completion = completion {
DispatchQueue.main.async {
completion()
}
}
}
}
}
so you can perform your actions in background and then, after the background finish, do something on main Thread

how to debug watch connectivity

I am attempting to start an HKWorkoutSession on the Apple Watch and send the heart rate data near-instantaneously to the iPhone for near real-time display. To accomplish this, I'm using WatchConnectivity's sendMessage method. I do not need replies from the phone/watch, so I'm using the version of sendMessage that doesn't use a reply handler.
The heart rate data isn't making it to the phone, and I'm struggling to understand why. I'm not getting any sorts of error messages that are helpful. How do I find out what is going wrong? I have attached both the phone app and the watch app to the debugger, but since the message never gets to the phone, I'm having a ton of trouble figuring out what's going on because obviously my breakpoints in the phone code aren't being reached. Earlier, I was using the replyHandler version of sendMessage, which has a closure for error handling. Using that, I was able to see that my errors were (sometimes) due a timeout in receiving a return message. The didReceiveMessage delegate on the phone was never reached, though, so I'm not surprised that it never sent its return message. I assume there's something wrong with the connection between the phone app and watch app, but I've checked the isReachable boolean, as well as isPaired and isWatchAppInstalled.
So I guess I'm wondering if you have any tips about debugging techniques for Watch Connectivity. And, if you want to take a look at my code too, here it is. Let me know if you see anything glaringly wrong about it. (Sorry it's a tad sloppy--just trying to get things to work right now.)
ViewController:
class ViewController: UIViewController, WCSessionDelegate {
#IBOutlet weak var bpmLabel: UILabel!
let healthStore = HKHealthStore()
var bpmArray = [Double]()
var wcSession: WCSession?
// WC Session Delegate methods
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
if let error = error {
print("WC Session activation failed with error: \(error.localizedDescription)")
return
}
}
func sessionDidBecomeInactive(_ session: WCSession) {
print("WC has become inactive")
}
func sessionDidDeactivate(_ session: WCSession) {
print("WC was deactivated")
}
func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
guard let bpm = message["bpm"] as? Double else { return }
DispatchQueue.main.async {
self.bpmArray.append(bpm)
self.bpmLabel.text = String(bpm)
}
override func viewDidLoad() {
super.viewDidLoad()
if WCSession.isSupported() {
wcSession = WCSession.default
wcSession?.delegate = self
wcSession?.activate()
}
if !(wcSession?.isPaired)! || !(wcSession?.isWatchAppInstalled)! {
print("PAIRING PROBLEM")
}
}
InterfaceController:
var wcSession: WCSession?
#IBOutlet var bpm: WKInterfaceLabel!
let healthStore = HKHealthStore()
var workoutSession: HKWorkoutSession?
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
if let error = error {
print("WC Session activation failed with error: \(error.localizedDescription)")
return
}
}
func workoutSession(_ workoutSession: HKWorkoutSession, didChangeTo toState: HKWorkoutSessionState, from fromState: HKWorkoutSessionState, date: Date) {
print("here")
}
func workoutSession(_ workoutSession: HKWorkoutSession, didFailWithError error: Error) {
print("Workout session failure")
}
override func awake(withContext context: Any?) {
super.awake(withContext: context)
workoutSession?.delegate = self
guard let wcSess = self.wcSession else { return }
wcSess.activate()
}
// modified from https://github.com/coolioxlr/watchOS-2-heartrate/blob/master/VimoHeartRate%20WatchKit%20App%20Extension/InterfaceController.swift
func createHeartRateStreamingQuery() -> HKQuery? {
if !HKHealthStore.isHealthDataAvailable() {
print("health data not available")
}
guard let quantityType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate) else { return nil }
let heartRateQuery = HKAnchoredObjectQuery(type: quantityType, predicate: nil, anchor: nil, limit: Int(HKObjectQueryNoLimit)) { (query, sampleObjects, deletedObjects, newAnchor, error) -> Void in
self.updateHeartRate(samples: sampleObjects)
}
heartRateQuery.updateHandler = {(query, samples, deleteObjects, newAnchor, error) -> Void in
self.updateHeartRate(samples: samples)
}
return heartRateQuery
}
// modified from https://github.com/coolioxlr/watchOS-2-heartrate/blob/master/VimoHeartRate%20WatchKit%20App%20Extension/InterfaceController.swift
func updateHeartRate(samples: [HKSample]?) {
guard let heartRateSamples = samples as? [HKQuantitySample] else { return }
guard let sample = heartRateSamples.first else { return }
let value = sample.quantity.doubleValue(for: HKUnit(from: "count/min"))
DispatchQueue.main.async() {
self.bpm.setText(String(UInt16(value)))
}
let dataToSendToPhone = ["bpm":String(value)]
if (wcSession?.isReachable)! {
self.wcSession?.sendMessage(dataToSendToPhone, replyHandler: nil)
}
else {
print("WC Session not reachable")
}
}
override func willActivate() {
super.willActivate()
if WCSession.isSupported() {
wcSession = WCSession.default
wcSession?.delegate = self
wcSession?.activate()
}
}
override func didDeactivate() {
super.didDeactivate()
}
#IBAction func recordIsTapped() {
let workoutConfiguration = HKWorkoutConfiguration()
workoutConfiguration.activityType = .other
workoutConfiguration.locationType = .unknown
// Inspired by https://developer.apple.com/library/content/samplecode/SpeedySloth/Introduction/Intro.html
do {
try self.workoutSession = HKWorkoutSession(configuration: workoutConfiguration)
healthStore.start(self.workoutSession!)
if HKHealthStore.isHealthDataAvailable() {
if let query = createHeartRateStreamingQuery() {
self.healthStore.execute(query)
}
}
else {
print("Healthkit unavailable")
}
}
catch {
fatalError(error.localizedDescription)
}
}

NSURLConnection leak in Swift

I've found several other articles about memory issues with NSURLConnection however none of them related to projects using ARC. My problem is that I make NSURLConnections every 0.5s (yes I know it would be better with sockets, but I don't have control over the API). When I open the debug inspector of xCode I could clearly see my used memory rising:
When I profile my application with instruments however - no leaks, no persistent storage across mark generations, simply nothing:
I've purposely decoupled all my other logic and created simple application to show my problem.
This is the main(and only) ViewController
import UIKit
class ViewController: UIViewController {
private var timer: NSTimer!
private var requests = [ServerRequest]()
override func viewDidAppear(animated: Bool)
{
self.timer = NSTimer(timeInterval: 0.5, target: self, selector: "refresh", userInfo: nil, repeats: true)
NSRunLoop.mainRunLoop().addTimer(self.timer, forMode: NSRunLoopCommonModes)
}
#objc private func refresh()
{
let urlRequest = NSURLRequest(URL: NSURL(string: "https://api.stackexchange.com/2.2/questions?order=desc&sort=activity&site=stackoverflow")!)
let serverRequest = ServerRequest(request: urlRequest){
[unowned self] result, error, request in
println("yaba daba duu")
self.requests.removeAll(keepCapacity: false)
}
requests.append(serverRequest)
serverRequest.send()
}
}
And here's my async connection delegate:
import Foundation
class ServerRequest: NSObject
{
private var request: NSURLRequest!
typealias completionType = (NSData?, NSError?, ServerRequest) -> ()
private var completion: completionType!
private var receivedData: NSMutableData?
private var connection: NSURLConnection?
init(request: NSURLRequest, completion: (NSData?, NSError?, ServerRequest) -> ())
{
super.init()
self.request = request
self.completion = completion
self.connection = NSURLConnection(request: self.request, delegate: self, startImmediately:false)
//this line will help connection is fired even while tere are touch events
self.connection?.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
NSURLCache.sharedURLCache().removeAllCachedResponses()
}
func send()
{
receivedData = NSMutableData()
self.connection?.start()
}
func abort()
{
self.connection?.cancel()
}
}
extension ServerRequest: NSURLConnectionDataDelegate, NSURLConnectionDelegate
{
func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse)
{
self.receivedData?.length = 0
}
func connection(connection: NSURLConnection, didReceiveData data: NSData)
{
self.receivedData?.appendData(data)
}
func connection(connection: NSURLConnection, didFailWithError error: NSError)
{
self.connection = nil
self.completion(nil, error, self)
}
func connectionDidFinishLoading(connection: NSURLConnection)
{
self.connection = nil
self.completion(receivedData, nil, self)
}
//MARK: https specific(canAuthenticateAgainstProtectionSpace is depraceted first in iOS 8)
func connection(connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: NSURLProtectionSpace) -> Bool
{
return protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust
}
func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge)
{
challenge.sender.useCredential(NSURLCredential(forTrust: challenge.protectionSpace.serverTrust), forAuthenticationChallenge: challenge)
challenge.sender.continueWithoutCredentialForAuthenticationChallenge(challenge)
}
func connection(connection: NSURLConnection, willCacheResponse cachedResponse: NSCachedURLResponse) -> NSCachedURLResponse? {
return nil
}
}
Please note that I need to connect to https server, so I need corresponding delegate methods. Also I've implemented cache methods because of some suggestions in SO that caching responses in NSURLConnection may cause my issues. Finally request is scheduled in "NSRunLoopCommonModes" mode because I need it alive while scrolling(although removing this line doesn't affect the issue anyway).
UPDATE
I've jut tried even without custom class with delegate and the result is pretty much the same. Just copy-paste following:
import UIKit
class ViewController: UIViewController {
private var timer: NSTimer!
override func viewDidAppear(animated: Bool)
{
self.timer = NSTimer(timeInterval: 0.5, target: self, selector: "refresh", userInfo: nil, repeats: true)
NSRunLoop.mainRunLoop().addTimer(self.timer, forMode: NSRunLoopCommonModes)
}
#objc private func refresh()
{
let urlRequest = NSURLRequest(URL: NSURL(string: "https://api.stackexchange.com/2.2/questions?order=desc&sort=activity&site=stackoverflow")!)
NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue.mainQueue())
{
response, data, error in
println("yaba daba duu")
}
}
}
And my memory pressure is again rising:

How to Call Web Service in Web Socket in iOS?

currently i am making chat application using Web Socket.
My question is How to Call Web Service in Web Socket ?
In iOS using swift you can use two Cocoapods Library which makes your work hassle free and
1) Starscream
2) RocketSocket
With reference to Starscream follow are very handy example:
import UIKit
import Starscream
class ViewController: UIViewController, WebSocketDelegate {
var socket: WebSocket!
override func viewDidLoad() {
super.viewDidLoad()
var request = URLRequest(url: URL(string: "http://localhost:8080")!)
request.timeoutInterval = 5
socket = WebSocket(request: request)
socket.delegate = self
socket.connect()
}
// MARK: Websocket Delegate Methods.
func websocketDidConnect(socket: WebSocketClient) {
print("websocket is connected")
}
func websocketDidDisconnect(socket: WebSocketClient, error: Error?) {
if let e = error as? WSError {
print("websocket is disconnected: \(e.message)")
} else if let e = error {
print("websocket is disconnected: \(e.localizedDescription)")
} else {
print("websocket disconnected")
}
}
func websocketDidReceiveMessage(socket: WebSocketClient, text: String) {
print("Received text: \(text)")
}
func websocketDidReceiveData(socket: WebSocketClient, data: Data) {
print("Received data: \(data.count)")
}
// MARK: Write Text Action
#IBAction func writeText(_ sender: UIBarButtonItem) {
socket.write(string: "hello there!")
}
// MARK: Disconnect Action
#IBAction func disconnect(_ sender: UIBarButtonItem) {
if socket.isConnected {
sender.title = "Connect"
socket.disconnect()
} else {
sender.title = "Disconnect"
socket.connect()
}
}
}

Swift: Receive UDP with GCDAsyncUdpSocket

BACKGROUND:
I want to be able to send and receive UDP packets between my iOS app and a server.
The server echoes back every incoming message to the client the app. The server is tested and confirmed working. I have a StartViewController which starting up two classes that implements GCDAsyncUdpSocketDelegate, one for sending and one for receiving. The "sending socket" is working, the server receives the messages.
PROBLEM:
The app never get the incoming message back after it been sent. Something with the listening socket setup is probably wrong since didReceiveData never get called.
Have I done this completely wrong?
Start:
class StartViewController: UIViewController {
var inSocket : InSocket!
var outSocket : OutSocket!
override func viewDidLoad() {
super.viewDidLoad()
inSocket = InSocket()
outSocket = OutSocket()
}
#IBAction func goButton(sender: UIButton) {
outSocket.send("This is a message!")
}
}
Receive:
class InSocket: NSObject, GCDAsyncUdpSocketDelegate {
let IP = "255.255.255.255"
let PORT:UInt16 = 5556
var socket:GCDAsyncUdpSocket!
override init(){
super.init()
setupConnection()
}
func setupConnection(){
var error : NSError?
socket = GCDAsyncUdpSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
socket.bindToPort(PORT, error: &error)
socket.enableBroadcast(true, error: &error)
socket.joinMulticastGroup(IP, error: &error)
socket.beginReceiving(&error)
}
func udpSocket(sock: GCDAsyncUdpSocket!, didReceiveData data: NSData!, fromAddress address: NSData!, withFilterContext filterContext: AnyObject!) {
println("incoming message: \(data)");
}
}
Send:
class OutSocket: NSObject, GCDAsyncUdpSocketDelegate {
let IP = "90.112.76.180"
let PORT:UInt16 = 5556
var socket:GCDAsyncUdpSocket!
override init(){
super.init()
setupConnection()
}
func setupConnection(){
var error : NSError?
socket = GCDAsyncUdpSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
socket.connectToHost(IP, onPort: PORT, error: &error)
}
func send(message:String){
let data = message.dataUsingEncoding(NSUTF8StringEncoding)
socket.sendData(data, withTimeout: 2, tag: 0)
}
func udpSocket(sock: GCDAsyncUdpSocket!, didConnectToAddress address: NSData!) {
println("didConnectToAddress");
}
func udpSocket(sock: GCDAsyncUdpSocket!, didNotConnect error: NSError!) {
println("didNotConnect \(error)")
}
func udpSocket(sock: GCDAsyncUdpSocket!, didSendDataWithTag tag: Int) {
println("didSendDataWithTag")
}
func udpSocket(sock: GCDAsyncUdpSocket!, didNotSendDataWithTag tag: Int, dueToError error: NSError!) {
println("didNotSendDataWithTag")
}
}
Edit:
Added forgotten code line.
I finally got it to work with this socket setup:
func setupConnection(){
var error : NSError?
socket = GCDAsyncUdpSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
socket.bindToPort(PORT, error: &error)
socket.connectToHost(SERVER_IP, onPort: PORT, error: &error)
socket.beginReceiving(&error)
send("ping")
}
func send(message:String){
let data = message.dataUsingEncoding(NSUTF8StringEncoding)
socket.sendData(data, withTimeout: 2, tag: 0)
}
Apple Swift version 4.2.1 Well Tested UDP Example:-
STEP 1 :- pod 'CocoaAsyncSocket'
STEP 2 :- import CocoaAsyncSocket in your UIViewController.
STEP 3 :- UIViewController
import UIKit
import CocoaAsyncSocket
class ViewController: UIViewController {
#IBOutlet weak var btnOnOff: LightButton!
#IBOutlet weak var lblStatus: UILabel!
var inSocket : InSocket!
var outSocket : OutSocket!
override func viewDidLoad() {
super.viewDidLoad()
lblStatus.isHidden = true
inSocket = InSocket()
outSocket = OutSocket()
outSocket.setupConnection {
self.lblStatus.isHidden = false
}
}
#IBAction func btnLight(_ sender: Any) {
let signal:Signal = Signal()
self.outSocket.send(signal: signal)
}
}
STEP 4 :- Reciving Socket
//Reciving End...
class InSocket: NSObject, GCDAsyncUdpSocketDelegate {
//let IP = "10.123.45.2"
let IP = "127.0.0.1"
let PORT:UInt16 = 5001
var socket:GCDAsyncUdpSocket!
override init(){
super.init()
setupConnection()
}
func setupConnection(){
socket = GCDAsyncUdpSocket(delegate: self, delegateQueue:DispatchQueue.main)
do { try socket.bind(toPort: PORT)} catch { print("")}
do { try socket.enableBroadcast(true)} catch { print("not able to brad cast")}
do { try socket.joinMulticastGroup(IP)} catch { print("joinMulticastGroup not proceed")}
do { try socket.beginReceiving()} catch { print("beginReceiving not proceed")}
}
//MARK:-GCDAsyncUdpSocketDelegate
func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?) {
print("incoming message: \(data)");
let signal:Signal = Signal.unarchive(d: data)
print("signal information : \n first \(signal.firstSignal) , second \(signal.secondSignal) \n third \(signal.thirdSignal) , fourth \(signal.fourthSignal)")
}
func udpSocket(_ sock: GCDAsyncUdpSocket, didNotConnect error: Error?) {
}
func udpSocketDidClose(_ sock: GCDAsyncUdpSocket, withError error: Error?) {
}
}
STEP 5 :- Sending Socket..
//Sending End...
class OutSocket: NSObject, GCDAsyncUdpSocketDelegate {
// let IP = "10.123.45.1"
let IP = "127.0.0.1"
let PORT:UInt16 = 5001
var socket:GCDAsyncUdpSocket!
override init(){
super.init()
}
func setupConnection(success:(()->())){
socket = GCDAsyncUdpSocket(delegate: self, delegateQueue:DispatchQueue.main)
do { try socket.bind(toPort: PORT)} catch { print("")}
do { try socket.connect(toHost:IP, onPort: PORT)} catch { print("joinMulticastGroup not proceed")}
do { try socket.beginReceiving()} catch { print("beginReceiving not proceed")}
success()
}
func send(signal:Signal){
let signalData = Signal.archive(w: signal)
socket.send(signalData, withTimeout: 2, tag: 0)
}
//MARK:- GCDAsyncUdpSocketDelegate
func udpSocket(_ sock: GCDAsyncUdpSocket, didConnectToAddress address: Data) {
print("didConnectToAddress");
}
func udpSocket(_ sock: GCDAsyncUdpSocket, didNotConnect error: Error?) {
if let _error = error {
print("didNotConnect \(_error )")
}
}
func udpSocket(_ sock: GCDAsyncUdpSocket, didNotSendDataWithTag tag: Int, dueToError error: Error?) {
print("didNotSendDataWithTag")
}
func udpSocket(_ sock: GCDAsyncUdpSocket, didSendDataWithTag tag: Int) {
print("didSendDataWithTag")
}
}
STEP 6 :- Your Signal Data which you will Send/Recieve
import Foundation
struct Signal {
var firstSignal:UInt16 = 20
var secondSignal:UInt16 = 30
var thirdSignal: UInt16 = 40
var fourthSignal: UInt16 = 50
static func archive(w:Signal) -> Data {
var fw = w
return Data(bytes: &fw, count: MemoryLayout<Signal>.stride)
}
static func unarchive(d:Data) -> Signal {
guard d.count == MemoryLayout<Signal>.stride else {
fatalError("BOOM!")
}
var s:Signal?
d.withUnsafeBytes({(bytes: UnsafePointer<Signal>)->Void in
s = UnsafePointer<Signal>(bytes).pointee
})
return s!
}
}

Resources