I'm trying to use Pusher for my iOS app. I installed Starscream.framework into my app as client side. I was able to connect to the specific Pusher's app. And also I was able to disconnect it by tapping a button on my app. I can watch these activities and logs from Debug Console of Pusher.
But, if I create new event from Debug Console, my iOS app doesn't receive it event."websocketDidReceiveMessage" function will not work. Image of Debug Console
I think that I made mistake. Please tell me if there is some kind of mistake.
Best regards.
Here is my code.
import UIKit
import Parse
import Starscream
class ViewController: UIViewController, WebSocketDelegate {
var socket = WebSocket(url: NSURL(scheme: "ws", host: "ws.pusherapp.com/app/API_KEY?protocol=7", path: "/")!)
override func viewDidLoad() {
super.viewDidLoad()
self.socket.delegate = self
self.socket.connect()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func disconnectWasTapped(sender: UIButton) {
self.socket.disconnect()
}
// MARK: WebSocket
func websocketDidConnect(socket: WebSocket) {
println("websocket is connected")
}
func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
println("websocket is disconnected: \(error?.localizedDescription)")
}
func websocketDidReceiveMessage(socket: WebSocket, text: String) {
//println("got some text!!")
println("got some text: \(text)")
}
func websocketDidReceiveData(socket: WebSocket, data: NSData) {
println("got some data: \(data.length)")
}
}
UPDATE
I was able to fix my problem by my self. I decided not to use Pusher. I decided to use PubNub instead Pusher. It is working on Swift now. And it is really easy to integrate with Parse to realize the realtime communication.
Related
I want to implement Single Sign On Extension for an iOS 13 app. I've already gone through various blogs, but there seems to be no standard solution available for implementing single sign-on extensions.
I'm trying to build up my own SSO solution, but I've not yet been able to implement it successfully. Here is the code that I have written so far:
import UIKit
import AuthenticationServices
class ViewController: UIViewController {
#IBOutlet weak var loginButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func loginButtonPushed(_ sender: Any) {
let issuer = URL(fileURLWithPath: "https://url_here")
let ssoProvider = ASAuthorizationSingleSignOnProvider(identityProvider: issuer)
let request = ssoProvider.createRequest()
request.requestedScopes = [.fullName, .email]
request.authorizationOptions = [
URLQueryItem(name: "client_id", value: "client_id"),
URLQueryItem(name: "response_type", value: "code")
]
let authzController = ASAuthorizationController(authorizationRequests: [request])
authzController.delegate = self
authzController.presentationContextProvider = self
authzController.performRequests()
}
}
extension ViewController: ASAuthorizationControllerDelegate {
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
}
func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
// Handle error.
}
}
extension ViewController: ASAuthorizationControllerPresentationContextProviding {
func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
return self.view.window!
}
}
More generally, I'd like to ask:
What are the prerequisites to an SSO solution that we need to consider before implementation.
Questions Like:
What type of server required,
Which auth services need to implement and why,
Do we need to consider Apple configurator2 for implementing this?
Is there anything that need to be done at server-side? If yes, please explain it. I need to understand both the back-end and development perspectives.
There are two different types of extensions provided by iOS 13 for SSO implementations: redirect and credential.
So, how should we decide which extension to implement and why? What circumstances do we need to consider in making the decision?
Here is an simple Swifter application in Swift 3.2 and xCode9.
Its working.
But I would write this application when this app is in background, then it bringing to front and I will see the standard white screen.
What is the best way for this idea?
import UIKit
import AudioToolbox
import WatchKit
import Foundation
import Swifter
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let server = HttpServer()
server["/hello"] = {
var queryParamsInfo = ""
for (name, value) in $0.queryParams {
queryParamsInfo += "\(name) -> \(value)<br/>"
}
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate)
return .ok(.html("<h3>You asked for \(queryParamsInfo)</h3>"))
}
do {
try server.start()
print("Server is started")
while true {
}
}
catch {
print("Error!")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Thanks for your help!
This is not possible on iOS. An application can only enter the foreground if
The user taps the app icon
The user taps a notification
The user brings the app to the foreground from the multitasking menu
The app is opened by another app (using URL Schemes)
You can not bring your app to the foreground programatically.
I have been trying to connect to a local server without success. My Code is as follows -
class SocketManager: NSObject, WebSocketDelegate {
var socket: WebSocket!
override init() {
super.init()
self.socket = WebSocket(url: NSURL(string: "ws://localhost:9292/")!)
self.socket.delegate = self
print("TRYING TO CONNECT")
self.socket.connect()
print("DONE TRYING")
}
func websocketDidConnect(ws: WebSocket) {
print("websocket is connected")
}
func websocketDidDisconnect(ws: WebSocket, error: NSError?) {
print("websocket is disconnected: \(error?.localizedDescription)")
}
func websocketDidReceiveMessage(ws: WebSocket, text: String) {
print("Received text: \(text)")
}
func websocketDidReceiveData(ws: WebSocket, data: NSData) {
print("Received data: \(data.length)")
}
func websocketDidReceivePong(socket: WebSocket) {
print("Got pong!")
}
}
Both the Print statements "TRYING TO CONNECT" and "DONE TRYING" are present in the log, but none of the delegate methods seem to be called.
I am not sure what could be wrong here.
Any help is appreciated.
The issue was that, I was creating an instance of the class SocketManager in the AppDelegate and that variable was falling out of scope.
To solve this, I created an instance variable in the AppDelegate, after doing that the delegate methods are being called as expected.
Here's a link to the issue that I posted on their Github repo.
https://github.com/daltoniam/Starscream/issues/203
Hope it helps.
For anyone still confused, the problem (for me) was that I was initialising and calling everything in viewDidLoad:
let client = WsClient(echoURL: "ws://localhost:8000/")
client.connect()
client.socket.write(string: "Hi Server!")
To fix this, I simply moved the client definition to be a property of ViewController, while keeping connect and write in viewDidLoad. This worked!
So now I have
class ViewController: UIViewController {
let client = WsClient(echoURL: "ws://localhost:8000/")
(...)
override func viewDidLoad() {
client.connect()
client.socket.write(string: "Hi Server!")
}
}
Between the pod spec and what is currently on S.O. I had a tough time figuring out how to get speech-to-text working using SpeechKit + CocoaPod + Swift. Finally got it working so figured I'd help the next poor soul that comes looking for help! :)
First install the CocoaPod: https://cocoapods.org/pods/SpeechKit
Add #import <SpeechKit/SpeechKit.h> to your bridging header
Login to Nuance's dev portal and create an app: https://developer.nuance.com/
Clean up the demo code so that is is more organized. I just wanted as much of the code to be in one place as possible so you can see a fully working implementation.
Then create a UIViewController and add the following code with the correct credentials:
import UIKit
import SpeechKit
class SpeechKitDemo: UIViewController, SKTransactionDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//!!link this to a corresponding button on the UIViewController in I.B.
#IBAction func tappedButton(sender: AnyObject) {
// All fields are required.
// Your credentials can be found in your Nuance Developers portal, under "Manage My Apps".
let SKSAppKey = "[Get this from the nuance app info page]";
let SKSAppId = "[Get this from the nuance app info page]";
let SKSServerHost = "[Get this from the nuance app info page]";
let SKSServerPort = "[Get this from the nuance app info page]";
let SKSLanguage = "eng-USA";
let SKSServerUrl = "nmsps://\(SKSAppId)#\(SKSServerHost):\(SKSServerPort)"
let session = SKSession(URL: NSURL(string: SKSServerUrl), appToken: SKSAppKey)
//this starts a transaction that listens for voice input
let transaction = session.recognizeWithType(SKTransactionSpeechTypeDictation,
detection: .Short,
language: SKSLanguage,
delegate: self)
print(transaction)
}
//required delegate methods
func transactionDidBeginRecording(transaction: SKTransaction!) { }
func transactionDidFinishRecording(transaction: SKTransaction!) { }
func transaction(transaction: SKTransaction!, didReceiveRecognition recognition: SKRecognition!) {
//Take the best result
let topRecognitionText = recognition.text;
print("Best rec test: \(topRecognitionText)")
//Or iterate through the NBest list
let nBest = recognition.details;
for phrase in (nBest as! [SKRecognizedPhrase]!) {
let text = phrase.text;
let confidence = phrase.confidence;
print("\(confidence): \(text)")
}
}
func transaction(transaction: SKTransaction!, didReceiveServiceResponse response: [NSObject : AnyObject]!) { }
func transaction(transaction: SKTransaction!, didFinishWithSuggestion suggestion: String!) { }
func transaction(transaction: SKTransaction!, didFailWithError error: NSError!, suggestion: String!) { }
}
I'm a newbie on IOS development. Recently, I use UIWebView to load a webpage, and this is successful, and try to open links in it on the same UIWebView instance. However, after a click on some link, there's no response from UIWebView, and in xcode, it reports
2015-03-29 23:42:07.246 xxxxx[17349:1251340] Unknown result for URL http://www.xxxxxx.org/bugs/xxxxxx-xxxx-xxxxxx, for frame
I looked it up on Internet but I got little useful help. I know someone said to implement func webView in UIWebViewDelegate, but my app still doesn't work.
Can someone help me? I'm using the latest version of swift language. And a snippet of code is :
import UIKit
class ViewController: UIViewController, UIWebViewDelegate {
#IBOutlet weak var front: UIWebView!
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType nt: UIWebViewNavigationType) -> Bool {
if (nt ==.LinkClicked){
return true
}
return true;
}
override func viewDidLoad() {
super.viewDidLoad()
UIWebView.loadRequest(self.front)(NSURLRequest(URL: NSURL(string: "http://www.google.com")!)) // Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Here is the sample Code :
UIWebView.loadRequest(webviewInstance)(NSURLRequest(URL: NSURL(string: "www.google.in")))