xmppStreamDidConnect not getting called in "swift framework" - swift

I'm creating the framework in swift, using cocoapods I have added XMPP framework but somehow can't able to connect to my host :
my set up:
class XMPPController: NSObject ,XMPPStreamDelegate{
var XMPP_HOST = "**************";
var userJid:XMPPJID = XMPPJID();
var password = "";
var xmppStream:XMPPStream;
init(jid: String, password: String) {
if let userjabberid = XMPPJID(string: jid) {
self.userJid = userjabberid;
}
self.password = password;
self.xmppStream = XMPPStream();
self.xmppStream.hostName = XMPP_HOST;
self.xmppStream.hostPort = 5222;
self.xmppStream.startTLSPolicy = XMPPStreamStartTLSPolicy.allowed;
self.xmppStream.myJID = self.userJid;
super.init();
self.xmppStream.addDelegate(self, delegateQueue: DispatchQueue.main)
}
and my connect method:
func connect() {
if !self.xmppStream.isDisconnected {
return
}
do {
try self.xmppStream.connect(withTimeout: XMPPStreamTimeoutNone);
} catch let err {
print(err);
}
}
and my delegate methods:
func xmppStreamWillConnect(_ sender: XMPPStream) {
print("will connect");
}
func xmppStream(_ sender: XMPPStream, socketDidConnect socket: GCDAsyncSocket) {
print("socket")
}
func xmppStreamDidStartNegotiation(_ sender: XMPPStream) {
print("negotiate")
}
func xmppStream(_ sender: XMPPStream, didReceiveError error: DDXMLElement) {
print(error);
}
func xmppStreamDidDisconnect(_ sender: XMPPStream, withError error: Error?) {
print("disconnected");
}
func xmppStreamDidConnect(_ sender: XMPPStream) {
print("connected");
try! sender.authenticate(withPassword: self.password);
}
func xmppStreamDidAuthenticate(_ sender: XMPPStream) {
print("authenticated");
}
func xmppStream(_ sender: XMPPStream, didNotAuthenticate error: DDXMLElement) {
print("Stream: Fail to Authenticate");
}
here, only xmppStreamWillConnect gets called and all other delegates methods are not called.

You need to init XMPPController like below and call connect function:
self.xmppController = XMPPController(jid: String, password: String)
self.xmppController.xmppStream.addDelegate(self, delegateQueue: DispatchQueue.main)
self.xmppController.connect()

solved by making singleton of my class as fallows:
static let sharedInstance = XMPPController();
And calling it as :
XMPPController.sharedInstance.connect(Withjid: "***#dev.****.com", Andpassword: "password");

I too was having same issue, later discovered that I had not started mongooseIM server.
Download from here
Step1: Start server
mongooseimctl start
Step2: Check status
mongooseimctl status
Step3: Create/Register User
mongooseimctl register itsyourusername localhost itsapassword
Step 4: Use these credential in XMPP client framework.
Official Docs

Related

ORSSerialPort with Arduino

I've been trying for a long time to program an Xcode interface to communicate with my Arduino Mega. but the whole thing didn't work as well as intended. I did the whole thing with ORSSerialPort.
In the Xcode project I wrote this for the swift file ViewController.swift :
import Cocoa
import ORSSerial
class ViewController: NSViewController, ORSSerialPortDelegate {
var serialPort = ORSSerialPort(path: "/dev/cu.usbmodem142101")
func SendString(data: String){
let stringData = Data(data.utf8)
serialPort?.send(stringData)
}
func openPort(){
serialPort?.baudRate=9600
serialPort?.delegate=self
serialPort?.parity = .none
serialPort?.numberOfStopBits = 1
serialPort?.open()
print("serialport is open")
}
func closePort(){
serialPort?.delegate=nil
serialPort?.close()
print("serialport is close")
}
override func viewDidLoad() {
super.viewDidLoad()
}
override var representedObject: Any? {
didSet {
}
}
#IBAction func onButton(_ sender: Any) {
openPort()
}
#IBAction func OffButton(_ sender: Any) {
closePort()
}
#IBAction func SendButton(_ sender: Any) {
SendString(data: "stringdata blablabla")
}
func serialPortWasOpened(_ serialPort: ORSSerialPort) {
print("serialPort to \(serialPort) is run")
}
func serialPortWasRemovedFromSystem(_ serialPort: ORSSerialPort) {
self.serialPort = nil
}
}
and this code i have load on the Arduino mega:
String angel;
void setup() {
Serial.begin(9600);
}
void loop() {
angel = Serial.readString();
Serial.println(angel);
delay(350);
}
unfortunately it doesn't work and I don't know why.
Your question doesn't provide any detail about what part(s) don't work, but there's one definite problem.
Your Arduino program looks like it echos everything it receives on the serial port back on the same port. In order to see that on the computer, you'll have to implement the serialPort(_:didReceive:) method in your view controller. Something like this:
func serialPort(_ serialPort: ORSSerialPort, didReceive data: Data) {
guard let string = String(data: data, encoding: .ascii) else { return; }
print("Received: \(string)")
}

delegate method does not get called second time

I am building a simple currency converter app. When ViewController gets opened it calls a function from CoinManager.swift:
class ViewController: UIViewController {
var coinManager = CoinManager()
override func viewDidLoad() {
super.viewDidLoad()
coinManager.delegate = self
coinManager.getCoinPrice(for: "AUD", "AZN", firstCall: true)
}
...
}
CoinManager.swift:
protocol CoinManagerDelegate {
func didUpdatePrice(price1: Double, currency1: String, price2: Double, currency2: String)
func tellTableView(descriptions: [String], symbols: [String])
func didFailWithError(error: Error)
}
struct CoinManager {
var delegate: CoinManagerDelegate?
let baseURL = "https://www.cbr-xml-daily.ru/daily_json.js"
func getCoinPrice (for currency1: String,_ currency2: String, firstCall: Bool) {
if let url = URL(string: baseURL) {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, response, error) in
if error != nil {
self.delegate?.didFailWithError(error: error!)
return
}
if let safeData = data {
if let coinData = self.parseJSON(safeData) {
if firstCall {
var descriptions = [""]
let listOfCoins = Array(coinData.keys)
for key in listOfCoins {
descriptions.append(coinData[key]!.Name)
}
descriptions.removeFirst()
self.delegate?.tellTableView(descriptions: descriptions, symbols: listOfCoins)
}
if let coinInfo1 = coinData[currency1] {
let value1 = coinInfo1.Value
if let coinInfo2 = coinData[currency2] {
let value2 = coinInfo2.Value
//this line does not do anything the second time I call getCoinPrice:
self.delegate?.didUpdatePrice(price1: value1, currency1: currency1, price2: value2, currency2: currency2)
//And this one does work
print("delegate:\(currency1)")
} else {
print("no name matches currency2")
}
} else {
print("no name matches currency1")
}
}
}
}
task.resume()
}
}
func ParseJSON....
}
The method it calls (ViewController.swift):
extension ViewController: CoinManagerDelegate {
func didUpdatePrice(price1: Double, currency1: String, price2: Double, currency2: String) {
print("didUpdatePrice called")
DispatchQueue.main.async {
let price1AsString = String(price1)
let price2AsString = String(price2)
self.leftTextField.text = price1AsString
self.rightTextField.text = price2AsString
self.leftLabel.text = currency1
self.rightLabel.text = currency2
}
}
...
}
and finally, CurrencyViewController.swift:
var coinManager = CoinManager()
#IBAction func backButtonPressed(_ sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
coinManager.getCoinPrice(for: "USD", "AZN", firstCall: false)
}
So when I launch the app i get following in my debug console:
didUpdatePrice called
delegate:AUD
And when I call getCoinPrice() from CurrencyViewController the delegate method does not get called. I know that my code goes through the delegate function line as I get this in debug console:
delegate:USD
I just can't wrap my head around it. The delegate method does not work when gets called second time. Even though it is called by the same algorithm
It's because you're creating a new object of CoinManager in CurrencyViewController where the delegate is not set. So you've to set the delegate every time you create a new instance of CoinManager.
#IBAction func backButtonPressed(_ sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
coinManager.delegate = self
coinManager.getCoinPrice(for: "USD", "AZN", firstCall: false)
}
Update: So, the above solution would require for you to make the delegate conformance in CurrencyViewController. If you're looking for an alternate solution you should probably pass the instance of coinManager in ViewController to CurrencyViewController. For that here are the things you need to update.
In CurrencyViewController:
class CurrencyViewController: UIViewController {
var coinManager: CoinManager! // you can optional unwrap if you intent to use CurrencyViewController without coinManager
//...
And in ViewController:
currencyViewController.coinManager = coinManager // passing the instance of coinManager
Can you share the full code of CoinManager? I see this part
if firstCall {
...
}
Maybe some block logic here or unhandled cases? And can you share the full code of protocol?
Also try to print something before this code:
if error != nil {
self.delegate?.didFailWithError(error: error!)
return
}

didInititate method for Spotify IOS SDK is not calling even though called sessionManager.initiateSession()

I'm going through Spotify's authentication process and am requesting the scopes appRemoteControl for my app to control music and userReadCurrentlyPlaying for current song. I set up everything from the SPTConfiguration, SPTSessionManager, and SPTAppRemote, and their required delegate methods (SPTAppRemoteDelegate, SPTSessionManagerDelegate, SPTAppRemotePlayerStateDelegate) as well as initiating a session with the requested scopes whenever the user presses a button but I can't get the method
func sessionManager(manager: SPTSessionManager, didInitiate session: SPTSession) {
appRemote.connectionParameters.accessToken = session.accessToken
appRemote.connect()
print(session.accessToken)
}
to trigger. The authentication process fully works as it goes into my spotify app and returns back to my application and plays a song from the configuration.playURI = "" , however, the method above never is called. I followed the spotify demo project but still does not work. Here is my full code
class LogInViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
let spotifyClientID = Constants.clientID
let spotifyRedirectURL = Constants.redirectURI
let tokenSwap = "https://***********.glitch.me/api/token"
let refresh = "https://***********.glitch.me/api/refresh_token"
lazy var configuration: SPTConfiguration = {
let configuration = SPTConfiguration(clientID: spotifyClientID, redirectURL: URL(string: "Lyrically://callback")!)
return configuration
}()
lazy var sessionManager: SPTSessionManager = {
let manager = SPTSessionManager(configuration: configuration, delegate: self)
if let tokenSwapURL = URL(string: tokenSwap), let tokenRefreshURL = URL(string: refresh) {
self.configuration.tokenSwapURL = tokenSwapURL
self.configuration.tokenRefreshURL = tokenRefreshURL
self.configuration.playURI = ""
}
return manager
}()
lazy var appRemote: SPTAppRemote = {
let appRemote = SPTAppRemote(configuration: configuration, logLevel: .debug)
appRemote.delegate = self
return appRemote
}()
#IBAction func logIn(_ sender: UIButton) {
let requestedScopes: SPTScope = [.appRemoteControl, .userReadCurrentlyPlaying]
sessionManager.initiateSession(with: requestedScopes, options: .default)
}
}
extension LogInViewController: SPTAppRemotePlayerStateDelegate {
func playerStateDidChange(_ playerState: SPTAppRemotePlayerState) {
print("state changed")
}
}
extension LogInViewController: SPTAppRemoteDelegate {
func appRemoteDidEstablishConnection(_ appRemote: SPTAppRemote) {
print("connected")
appRemote.playerAPI?.delegate = self
appRemote.playerAPI?.subscribe(toPlayerState: { (success, error) in
if let error = error {
print("Error subscribing to player state:" + error.localizedDescription)
}
})
}
func appRemote(_ appRemote: SPTAppRemote, didFailConnectionAttemptWithError error: Error?) {
print("failed")
}
func appRemote(_ appRemote: SPTAppRemote, didDisconnectWithError error: Error?) {
print("disconnected")
}
}
extension LogInViewController: SPTSessionManagerDelegate {
func sessionManager(manager: SPTSessionManager, didInitiate session: SPTSession) {
appRemote.connectionParameters.accessToken = session.accessToken
appRemote.connect()
print(session.accessToken)
}
func sessionManager(manager: SPTSessionManager, didFailWith error: Error) {
print("failed",error)
}
}
Figured it out. Had to get a hold of the sessionManager from the LogInViewController by making an instance of it
lazy var logInVC = LogInViewController()
then added this line of code into the openURLContexts method in scene delegate
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
print("Opened url")
guard let url = URLContexts.first?.url else {
return
}
logInVC.sessionManager.application(UIApplication.shared, open: url, options: [:])
}

Bonjour Service Browser with Swift does not fetch serviceinfo

The service I want to connect to is published via Bonjour.
I can find all the info with the Bonjour Browser, however if I try to gather the data programmatically, the only value I get, is the name of the service.
The NetService delegate is set and the function netServiceWillPublish is called.
The functions DidNotPublish or DidPublish are not executed.
The function netServiceBrowser gets all published netServices, but all properties are set to the default value of the datatype.
import UIKit
class BMNSDelegate : NSObject, NetServiceDelegate {
func netServiceWillPublish(_ sender: NetService) {
print("netServiceWillPublish:\(sender)"); //This method is called
}
func netService(_ sender: NetService, didNotPublish errorDict: [String : NSNumber]){
print("didNotPublish:\(sender)");
}
func netServiceDidPublish(_ sender: NetService) {
print("netServiceDidPublish:\(sender)");
}
func netServiceWillResolve(_ sender: NetService) {
print("netServiceWillResolve:\(sender)");
}
func netService(_ sender: NetService, didNotResolve errorDict: [String : NSNumber]) {
print("netServiceDidNotResolve:\(sender)");
}
func netServiceDidResolveAddress(_ sender: NetService) {
print("netServiceDidResolve:\(sender)");
}
func netService(_ sender: NetService, didUpdateTXTRecord data: Data) {
print("netServiceDidUpdateTXTRecordData:\(sender)");
}
func netServiceDidStop(_ sender: NetService) {
print("netServiceDidStopService:\(sender)");
}
func netService(_ sender: NetService,
didAcceptConnectionWith inputStream: InputStream,
outputStream stream: OutputStream) {
print("netServiceDidAcceptConnection:\(sender)");
}
}
class BMBrowserDelegate : NSObject, NetServiceBrowserDelegate, NetServiceDelegate {
func netServiceBrowser(_ netServiceBrowser: NetServiceBrowser,
didFind netService: NetService,
moreComing moreServicesComing: Bool) {
let nsnsdel = BMNSDelegate()
netService.delegate = nsnsdel
netService.resolve(withTimeout: 1)
print(netService.domain) // local.
print(netService.name) // This property is correct
print(netService.type) // _http._tcp.
print(netService.addresses) // Optional([])
print(netService.hostName) // nil
print(netService.port) // -1
print(moreServicesComing) //false
}
}
let SERVICE_TYPE = "_http._tcp."
let BM_DOMAIN = "local."
let browser = NetServiceBrowser()
let nsbdel = BMBrowserDelegate()
browser.delegate = nsbdel
browser.searchForServices(ofType: SERVICE_TYPE, inDomain: BM_DOMAIN)
RunLoop.current.run()
The error is that the services which are found in the ServiceBrowserDelegate function are not saved anywhere and therefore are discarded at the end of the function.
I found a working example here:
https://github.com/mattneub/Programming-iOS-Book-Examples/blob/61f0c753a080040e4a74b912e6c18dd97fe8bcaa/bk2ch24p853bonjour/ch37p1101bonjour/ViewController.swift
class ViewController: UIViewController, NetServiceBrowserDelegate, NetServiceDelegate {
var nsb : NetServiceBrowser!
var services = [NetService]()
#IBAction func doButton (_ sender: Any!) {
print("listening for services...")
self.services.removeAll()
self.nsb = NetServiceBrowser()
self.nsb.delegate = self
self.nsb.searchForServices(ofType:"_daap._tcp", inDomain: "")
}
func updateInterface () {
for service in self.services {
if service.port == -1 {
print("service \(service.name) of type \(service.type)" +
" not yet resolved")
service.delegate = self
service.resolve(withTimeout:10)
} else {
print("service \(service.name) of type \(service.type)," +
"port \(service.port), addresses \(service.addresses)")
}
}
}
func netServiceDidResolveAddress(_ sender: NetService) {
self.updateInterface()
}
func netServiceBrowser(_ aNetServiceBrowser: NetServiceBrowser, didFind aNetService: NetService, moreComing: Bool) {
print("adding a service")
self.services.append(aNetService)
if !moreComing {
self.updateInterface()
}
}
func netServiceBrowser(_ aNetServiceBrowser: NetServiceBrowser, didRemove aNetService: NetService, moreComing: Bool) {
if let ix = self.services.index(of:aNetService) {
self.services.remove(at:ix)
print("removing a service")
if !moreComing {
self.updateInterface()
}
}
}
}

Swift/Stripe error communicating with the Parse Cloud Code

I have been working for days trying to figure out how to charge a card and save the card to a customer with Stripe using Swift, with Parse.com Cloud Code as the backend. I integrated the Stripe pod with my project successfully, and I have a token that is created, and prints out in the console to verify its existence. BUT I cannot do anything with it! I have searched everywhere for answers, and cannot figure out why I keep getting error. I think it has to do with the parameters that I am trying to feed to the Cloud Code, but I am unsure. I have read the docs for both Cloud Code and Stripe, and it was to no avail. This is my PaymentViewController.swift:
import UIKit
import Stripe
import PaymentKit
import Parse
import Bolts
class PaymentViewController: UIViewController, PTKViewDelegate {
#IBOutlet weak var saveBtn: UIButton!
var paymentView: PTKView = PTKView()
override func viewDidLoad() {
super.viewDidLoad()
var view : PTKView = PTKView(frame: CGRectMake(15,20,290,55))
paymentView = view
paymentView.delegate = self;
self.view.addSubview(self.paymentView)
saveBtn.enabled = false
}
func paymentView(view: PTKView!, withCard card: PTKCard!, isValid valid: Bool) {
if (valid) {
saveBtn.enabled = true
} else {
saveBtn.enabled = false
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func save(sender: AnyObject) {
var card: STPCard = STPCard()
card.number = self.paymentView.card.number
card.expMonth = self.paymentView.card.expMonth
card.expYear = self.paymentView.card.expYear
card.cvc = self.paymentView.card.cvc
STPAPIClient.sharedClient().createTokenWithCard(card, completion: { (tokenId: STPToken?, error: NSError?) -> Void in
if (error != nil) {
println(error)
println("what the..")
} else {
println(tokenId)
PFCloud.callFunctionInBackground("hello", withParameters: nil) {
(response: AnyObject?, error: NSError?) -> Void in
let responseString = response as? String
println(responseString)
}
PFCloud.callFunctionInBackground("createCharge", withParameters: nil, block: { (success: AnyObject?, error: NSError?) -> Void in
if error != nil {
println("error")
}
})
}
})
}
#IBAction func cancel(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
I have added the "Hello World" example to see if the Cloud Code was set up correctly, and that callFunction does work. My Cloud Code is:
var Stripe = require('stripe');
Stripe.initialize('My_Secret_Key');
Parse.Cloud.define("hello", function(request, response) {
response.success("Hello world!");
});
Parse.Cloud.define("createCharge", function(request, response) {
Stripe.Charges.create({
amount: 100 * 10, // $10 expressed in cents
currency: "usd",
card: "tok_3TnIVhEv9P24T0"
},{
success: function(httpResponse) {
response.success("Purchase made!");
},
error: function(httpResponse) {
response.error("Uh oh, something went wrong");
}
});
});
Any help would be truly appreciated!! I have been working tirelessly to figure this out! The console prints out
Uh oh, something went wrong (Code: 141, Version: 1.7.2)
The error you are seeing Uh oh, something went wrong (Code: 141, Version: 1.7.2) means that your createCharge Parse function returned an error. You may want to log the value of httpResponse to find the exact error from Stripe.
Looking at your code the error is most likely: Invalid Request Error: Cannot use token tok_3TnIVhEv9P24T0 more than once. You can confirm this in the Logs section of your Stripe Dashboard.
I see that you print the token, println(tokenId), you're also going to want to send that to your Parse function and set card equal to the value of the token you just created.
class PaymentViewController: UIViewController, PTKViewDelegate {
#IBOutlet weak var saveBtn: UIButton!
var paymentView: PTKView = PTKView()
override func viewDidLoad() {
super.viewDidLoad()
var view : PTKView = PTKView(frame: CGRectMake(15,20,290,55))
paymentView = view
paymentView.delegate = self;
self.view.addSubview(self.paymentView)
saveBtn.enabled = false
}
func paymentView(view: PTKView!, withCard card: PTKCard!, isValid valid: Bool) {
if (valid) {
saveBtn.enabled = true
} else {
saveBtn.enabled = false
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func save(sender: AnyObject) {
var card: STPCard = STPCard()
card.number = self.paymentView.card.number
card.expMonth = self.paymentView.card.expMonth
card.expYear = self.paymentView.card.expYear
card.cvc = self.paymentView.card.cvc
STPAPIClient.sharedClient().createTokenWithCard(card, completion: { (token: STPToken?, error: NSError?) -> Void in
if (error != nil) {
println(error)
println("not working")
} else {
//println(tokenId)
var coin = token!.tokenId
PFCloud.callFunctionInBackground("hello", withParameters: nil) {
(response: AnyObject?, error: NSError?) -> Void in
let responseString = response as? String
println(responseString)
}
var name = PFUser.currentUser()?.username as String!
var customer = PFUser.currentUser()?.objectId as String!
PFCloud.callFunctionInBackground("createCustomer", withParameters: ["coin" : coin, "name": name, "customer": customer], block: { (success: AnyObject?, error: NSError?) -> Void in
if error != nil {
println("create customer not working")
}
})
var customerId = customer!
PFCloud.callFunctionInBackground("createCharge", withParameters: ["customerId" : customerId], block: { (success: AnyObject?, error: NSError?) -> Void in
if error != nil {
println("not working")
}
})
}
})
}
#IBAction func cancel(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
And My updated cloud code is here:
var Stripe = require('stripe');
Stripe.initialize('sk_test_xxxxxxxxxxxxxx');
Parse.Cloud.define("hello", function(request, response) {
response.success("Hello world!");
});
Parse.Cloud.define("createCustomer", function(request, response) {
                   Stripe.Customers.create({
 card: request.params.coin,
account_balance: -10*100,
metadata: {
name: request.params.name,
customer: request.params.customer, // e.g PFUser object ID
}
 }, {
 success: function(customer) {
response.success(customer.id);
},
error: function(error) {
response.error("Error:" +error);
 }
})
                   });
 
Parse.Cloud.define("createCharge", function(request, response) {
Stripe.Charges.create({
amount: 100 * 10, // $10 expressed in cents
currency: "usd",
//card: request.params.coin
customer: request.params.customerId
},{
success: function(httpResponse) {
response.success("Purchase made!");
},
error: function(httpResponse) {
response.error(httpResponse)
response.error("Uh oh, something went wrong");
}
});
});
Ultimately I want to have the create customer in a different viewController.swift file and charge on another section of the app, but for right now I am testing it with them in the same PaymentViewController.swift file