How to use receiveReply method of func class

Best Nimble code snippet using func.receiveReply

Run Nimble automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

UDPFramework.swift

Source: UDPFramework.swift Github

copy
1//
2//  UDPFramework.swift
3//  UDP Framework
4//
5//  Created by Charles Vercauteren on 12/01/2022.
6//
7
8import Foundation
9import Network
10
11protocol UDPMessages {
12    func serverReady()
13    func receivedMessage(message: String)
14}
15
16class UDPFramework {
17    var delegate: UDPMessages?
18    var server: NWConnection?
19    var reply = ""
20    
21    func connect(host: NWEndpoint.Host, port: NWEndpoint.Port){
22        server = NWConnection(host: host, port: port, using: NWParameters.udp)
23        server?.stateUpdateHandler = stateUpdateHandler(newState:)
24        server?.start(queue: .main)
25    }
26    
27    func sendPacket(text: String) {
28        server!.send(content: text.data(using: String.Encoding.ascii), completion: .contentProcessed({
29            error in
30                self.receiveReply()
31                if let error = error {
32                    print("error while sending data: \(error).")
33                    return
34                }
35            }))}
36    
37    func disconnect() {
38        server?.forceCancel()
39    }
40    
41    
42    private func stateUpdateHandler(newState: NWConnection.State){
43        switch (newState){
44        case .setup:
45            print("State: Setup.")
46        case .waiting:
47            print("State: Waiting.")
48        case .ready:
49            print("State: Ready.")
50            delegate?.serverReady()
51        case .failed:
52            print("State: Failed.")
53        case .cancelled:
54            print("State: Cancelled.")
55        default:
56            print("State: Unknown state.")
57        }
58    }
59    
60    func receiveReply() {
61        server?.receiveMessage(completion: {(content, context,   isComplete, error) in
62            self.reply = String(decoding: content ?? Data(), as:   UTF8.self)
63            if self.reply != "", isComplete {
64                self.delegate?.receivedMessage(message: self.reply)
65                self.receiveReply()
66
67            }
68            })}
69    
70}
71
Full Screen

DeviceManager.swift

Source: DeviceManager.swift Github

copy
1//
2//  DeviceManager.swift
3//  Paqure
4//
5//  Created by Linguri Technology on 7/21/16.
6//  Copyright © 2016 Digices. All rights reserved.
7//
8
9import UIKit
10
11protocol DeviceManagerDelegate {
12    func deviceObjectSynced(success: Bool)
13}
14
15public class DeviceManager {
16    
17    public static var sharedInstance : DeviceManager = DeviceManager()
18    
19    var controller : DeviceManagerDelegate?
20    
21    var object : Device = Device()
22        
23    var source : Source = Source.DEFAULT
24    
25    let url = NSURL(string: "https://www.digices.com/api/device.php")
26
27    // stubs for localization keys
28    let s = NSLocalizedString("device_settings", comment: "The preferences and settings for the device")
29    let u = NSLocalizedString("update", comment: "Update record in database")
30
31    private init() {
32        
33        // DEBUG
34        print("DeviceManager.init()")
35        
36        // attempt to replace default device with stored device
37        if self.pullFromLocal() == true {
38            self.source = Source.LOCAL
39        } else {
40            self.saveToLocal()
41        }
42        
43        // remote will detect if default condition exists
44        self.pushToRemote()
45        
46    }
47    
48    func setController(controller: DeviceManagerDelegate) {
49        // DEBUG
50        print("DeviceManager.setController()")
51        
52        self.controller = controller
53    }
54    
55    func pullFromLocal() -> Bool {
56        // DEBUG
57        print("DeviceManager.pullFromLocal()")
58        
59        let storedObject = defaults.objectForKey("device")
60        if let retrievedObject = storedObject as? NSData {
61            if let unarchivedObject = NSKeyedUnarchiver.unarchiveObjectWithData(retrievedObject) {
62                if let device = unarchivedObject as? Device {
63                    self.object = device
64                    return true
65                } else {
66                    return false
67                }
68            } else {
69                return false
70            }
71        } else {
72            return false
73        }
74    }
75    
76    func pushToRemote() {
77        // DEBUG
78        print("DeviceManager.pushToRemote()")
79        
80        let request = NSMutableURLRequest(URL: self.url!)
81        request.HTTPMethod = "POST"
82        request.HTTPBody = self.object.encodedPostBody()
83        let task = session.dataTaskWithRequest(request, completionHandler: receiveReply)
84        task.resume()
85    }
86    
87    func receiveReply(data : NSData?, response: NSURLResponse?, error: NSError?) {
88        // DEBUG
89        print("DeviceManager.receiveReply()")
90        
91        if let error = error {
92            print(error.description)
93        }
94        // initialize parameter to pass to delegate
95        var success : Bool = false
96        
97        if let data = data {
98            do {
99                let parsedObject = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
100                if let parsedDevice = parsedObject["device"] {
101                    if let device = parsedDevice as? NSDictionary {
102                        let remoteDevice = Device(dict: device)
103                        if remoteDevice.id > 0 {
104                            self.object = remoteDevice
105                            self.source = Source.REMOTE
106                            self.saveToLocal()
107                            self.source = Source.SYNCED
108                            success = true
109                        }
110                    } else {
111                        print("object did not evaluate")
112                    }
113                } else {
114                    print("key \"device\" does not exist in data")
115                }
116            } catch {
117                print("serialization failed")
118            }
119        } else {
120            print("no data received")
121        }
122        
123        NSOperationQueue.mainQueue().addOperationWithBlock({
124            if success == true {
125                self.source = Source.SYNCED
126                self.controller?.deviceObjectSynced(true)
127            } else {
128                self.controller?.deviceObjectSynced(false)
129            }
130        })
131        
132    }
133    
134    func saveToLocal() {
135        // DEBUG
136        print("DeviceManager.saveToLocal()")
137
138        let data = NSKeyedArchiver.archivedDataWithRootObject(self.object)
139        defaults.setObject(data, forKey: "device")
140        self.source = Source.LOCAL
141    }
142    
143}
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)