GithubHelp home page GithubHelp logo

swiftr's Introduction

SwiftR

Join the chat at https://gitter.im/adamhartford/SwiftR

A Swift client for SignalR. Supports hubs and persistent connections.

Demo

I have published a sample SignalR server at http://swiftr.azurewebsites.net. The iOS demo application now uses this server. See SwiftRChat for the souce code. It's based on this, with some minor changes:

http://www.asp.net/signalr/overview/deployment/using-signalr-with-azure-web-sites

How does it work?

It's a wrapper around the SignalR JavaScript client running in a hidden web view. As such, it's subject to the same limitations of that client -- namely, no support for custom headers when using WebSockets. This is because the browser's WebSocket client does not support custom headers.

UIWebView or WKWebView?

Either, your choice. Note that since WKWebView runs in a separate process, it does not have access to cookies in NSHTTPCookieStorage. If you need cookies, use UIWebView. SwiftR uses UIWebView by default, but you can choose WKWebView instead:

// Client
let connection = SignalR("https://swiftr.azurewebsites.net")
connection.useWKWebView = true

Also when using WKWebView, make sure to enable CORS on your server:

// Server
app.UseCors (CorsOptions.AllowAll);

// See my SignalRApplication repo for a CORS example with ASP.NET Core.

How to set Origin

If allowing all origins (*) is not acceptable, you can specify an allowed origin via the originUrlString property.

connection.originUrlString = "http://www.example.com"

What versions of SignalR are supported?

SwiftR supports SignalR version 2.x. Version 2.2.2 is assumed by default. To change the SignalR version:

let connection = SignalR("https://swiftr.azurewebsites.net")
connection.signalRVersion = .v2_2_2
//connection.signalRVersion = .v2_2_1
//connection.signalRVersion = .v2_2_0
//connection.signalRVersion = .v2_1_2
//connection.signalRVersion = .v2_1_1
//connection.signalRVersion = .v2_1_0
//connection.signalRVersion = .v2_0_3
//connection.signalRVersion = .v2_0_2
//connection.signalRVersion = .v2_0_1
//connection.signalRVersion = .v2_0_0

Installation

CocoaPods:

use_frameworks!
pod 'SwiftR'

Carthage:

github 'adamhartford/SwiftR'

Server Example

See https://github.com/adamhartford/SignalRDemo for a sample self-hosted SignalR application. Or, https://github.com/adamhartford/SignalRApplication for an ASP.NET 5 version.

Simple Example (Hub)

// Server
public class SimpleHub : Hub 
{
    public void SendSimple(string message, string detail)
    {
        Clients.All.notifySimple (message, detail);
    }
}

Default parameter names in callback response:

// Client
let connection = SignalR("http://localhost:5000")

let simpleHub = Hub("simpleHub")
simpleHub.on("notifySimple") { args in
    let message = args![0] as! String
    let detail = args![1] as! String
    print("Message: \(message)\nDetail: \(detail)")
}

connection.addHub(simpleHub)
connection.start()

...

// Invoke server method
simpleHub.invoke("sendSimple", arguments: ["Simple Test", "This is a simple message"])

// Invoke server method and handle response
simpleHub.invoke("sendSimple", arguments: ["Simple Test", "This is a simple message"]) { (result, error) in
    if let e = error {
        print("Error: \(e)")
    } else {
        print("Success!")
        if let r = result {
            print("Result: \(r)")
        }
    }
}

Complex Example (Hub)

// Server
public class ComplexMessage
{
    public int MessageId { get; set; }
    public string Message { get; set; }
    public string Detail { get; set; }
    public IEnumerable<String> Items { get; set; }
}

// Server
public class ComplexHub : Hub
{
    public void SendComplex(ComplexMessage message) 
    {
        Clients.All.notifyComplex (message);
    }
}
// Client
let connection = SignalR("http://localhost:5000")

let complexHub = Hub("complexHub")
complexHub.on("notifyComplex") { args in
    let m: AnyObject = args![0] as AnyObject!
    print(m)
}

connection.addHub(complexHub)
connection.start()

...

let message = [
    "messageId": 1,
    "message": "Complex Test",
    "detail": "This is a complex message",
    "items": ["foo", "bar", "baz"]
]

// Invoke server method
complexHub.invoke("sendComplex", parameters: [message])

Persistent Connections

// Server
app.MapSignalR<MyConnection> ("/echo");

...

public class MyConnection : PersistentConnection 
{
    protected override Task OnReceived(IRequest request, string connectionId, string data) 
    {
        return Connection.Broadcast(data);
    }
}
// Client
let persistentConnection = SignalR("http://localhost:8080/echo", connectionType: .persistent)
persistentConnection.received = { data in
    print(data)
}
persistentConnection.start()

// Send data
persistentConnection.send("Persistent Connection Test")

Transport Method

By default, SignalR will choose the best transport available to you. You can also specify the transport method:

let connection = SignalR("https://swiftr.azurewebsites.net")
connection.transport = .auto // This is the default
connection.transport = .webSockets
connection.transport = .serverSentEvents
connection.transport = .foreverFrame
connection.transport = .longPolling

Connection Lifetime Events

SwiftR exposes the following SignalR events:

let connection = SignalR("http://swiftr.azurewebsites.net")
connection.started = { print("started") }
connection.connected = { print("connected: \(connection.connectionID)") }
connection.connectionSlow = { print("connectionSlow") }
connection.reconnecting = { print("reconnecting") }
connection.reconnected = { print("reconnected") }
connection.disconnected = { print("disconnected") }
connection.start()

Reconnecting

You may find it necessary to try reconnecting manually once disconnected. Here's an example of how to do that:

connection.disconnected = {
    print("Disconnected...")
    
    // Try again after 5 seconds
    let delayTime = DispatchTime.now() + .seconds(5)
    DispatchQueue.main.asyncAfter(deadline: delayTime) { [weak self] in
        connection.start()
    }
}

Stop/Start Connection

Use the stop() and start() methods to manage connections manually.

let connection  = SignalR("https://swiftr.azurewebsites.net")
connection.start()
connection.stop()

...

if connection.state == .connected {
    connection.stop()
} else if connection.state == .disonnected {
    connection.start()
}

Connection State

public enum State {
    case connecting
    case connected
    case disconnected
}

Sending information to SignalR

Query String

let connection = SignalR("https://swiftr.azurewebsites.net")
connection.queryString = ["foo": "bar"]

Custom Headers (Non-WebSocket Only)

let connection = SignalR("https://swiftr.azurewebsites.net")
connection.headers = ["X-MyHeader1": "Value1", "X-MyHeader2", "Value2"]

Cookies (UIWebView Only)

SwiftR will send any cookies in your app's NSHTTPCookieStorage to SignalR. You can also set cookies manually:

let cookieProperties = [
    NSHTTPCookieName: "Foo",
    NSHTTPCookieValue: "Bar",
    NSHTTPCookieDomain: "myserver.com",
    NSHTTPCookiePath: "/",
]
let cookie = NSHTTPCookie(properties: cookieProperties)
NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookie(cookie!)

Error Handling

connection.error = { error in 
  print("Error: \(error)")
  
  if let source = error?["source"] as? String, source == "TimeoutException" {
      print("Connection timed out. Restarting...")
      connection.start()
  }
}

License

SwiftR is released under the MIT license. See LICENSE for details.

swiftr's People

Contributors

adamhartford avatar eabadjiev avatar gitter-badger avatar mqhong avatar remylivewall avatar sandychapman avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swiftr's Issues

Invoke method doesn't work with single quote & line translation

When I send a string with single quote (') or line translation (\n) as an argument into invoke method, it doesn't return anything

let message = "FirsLine\n SecondLine\n SingleQuote' "
hub!.invoke("sendMessage", arguments: [message]){ (result, error) in
      print("SendMessage result: \(result)  error: \(error)")
}

I guess that in that case we'll get syntax error in JavaScript
Because I'm debugging invoke method in SwiftR.swift & variable «js» has this value

SwiftR.swift:476 connection.runJavaScript(js)
js  String  "ensureHub('chathub').invoke('sendMessage', 'FirsLine\n SecondLine\n SingleQuote' ').done(function() { postMessage({ message: 'invokeHandler', hub: 'chathub', id: '7DBE8B14-D170-4CB9-8332-3A29E96E0374', result: arguments[0] }); }).fail(function() { postMessage({ message: 'invokeHandler', hub: 'chathub', id: '7DBE8B14-D170-4CB9-8332-3A29E96E0374', error: processError(arguments[0]) }); })"  

Any ideas on how to resolve the issue?
Thanks

Expected Declaration

Hello @adamhartford again it's me... it's been a while I used SwiftR because I was working with some other stuffs. Now I was trying to make the Hub global by creating a class. When I tried to Add SwiftR I am getting an error saying expected declaration . Please check the Image..
errorswiftr

But able to get it work on my pervious screens... what's happening here ???

Fail to start connection after a few re-initiation

Hello dear developers,

I've been using this library to simulate some sort of chatroom between 2 client with a server in between.
Each time I select a client, I'll start a signal R connection from both side, and terminate it by the end of the session.

This will prompting the following event of the library in following sequence connection.starting -> connection.connecting -> connection.connected -> connection.disconnected.

However after roughly 4~5 round of above sequence, the connection will be stucked at connection.starting.... forever (not connecting, not disconnecting)

Can i know what could be the possible lead to this situtation? Am i not stopping the signalR connection properly or utilizing it the wrong way?

Thanks

Connection State shows "Starting" but not getting connected

Able to send 4 messages continuously but on sending the 5th message nothing else happens other than printing this message "Starting"

 SwiftR.connect("http://url/signalr/")
            {
                connection in
                    let signalrHub = connection.createHubProxy("chatHub")
                print("HUb : \(signalrHub)")

                signalrHub.on("recevivemessage")
                    {
                        args in
                            print("Response from Server : \(args)")
                        let message = JSQMessage(senderId: senderId, senderDisplayName: senderDisplayName, date: date, text: text)
                        self.messages += [message]
                        self.finishSendingMessage()
                    }

                connection.connected = {
                     self._userHubId = signalrHub.connection.connectionID!
                     print("Current Signalr id : \(self._userHubId)")
}
 connection.disconnected = {

                    print("Disconnected")

                    // Try again after 5 seconds
                    let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(5 * Double(NSEC_PER_SEC)))
                    dispatch_after(delayTime, dispatch_get_main_queue()) {
                        connection.start()
                    }

                }

                connection.connectionSlow = {
                    print("Connection slow")
                }

                connection.reconnecting = {
                    print("Reconnecting")
                }

                connection.reconnected  = {
                    print("Reconnected"
                }

                connection.starting = {
                    print("Starting")
                }
```)

I am getting SwiftR.Hub even at the fifth message but nothing more ... Any Idea about the situation?

Change user-agent

Hi,

How can i change the user agent of the SignalR connection ?
Thank you by advance

complexHub.invoke ---> fatal error: unexpectedly found nil while unwrapping an Optional value

I tried to follow your ways of writing in that page also I tried to applied without :[String, AnyObject] to this message or with it.. I tried with many various possible to assign this. I always end up with this same fatal error like this..

fatal error: unexpectedly found nil while unwrapping an Optional value

func adamsWay() {
SwiftR.connect("http://neverland.com:8080/configserver/signalr/hubs") { [weak self] connection in
self?.complexHub = connection.createHubProxy("lPConfigServer")

        self?.complexHub.on("getNewOnlineUser") { args in
            let m: AnyObject = args!["0"] as AnyObject!
            println(m)
        }
    }

    let message: [String: AnyObject] = [
        "messageId": 1,
        "message": "Complex Test",
        "detail": "This is a complex message",
        "items": ["foo", "bar", "baz"]
    ]

   // Invoke server method
    complexHub.invoke("getConnected", arguments: [message])  <<<< Something is going on with issue of [AnyObject]? here within that argument part.. Any suggest to resolve that? 
}

working in background thread

I'm developing this app which receives a lot of pushes, and since I start swiftR in the main thread, after connecting the app becomes very slow and nearly useless, I tried starting swift r in an async thread like this:

    let signalRQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
    dispatch_async(signalRQueue) {
        Networking.startSignalRConnection()
    }

but I get and exception on line:

webView = SwiftRWebView()
1   0x184b2fa94 <redacted>
2   0x180d08fe4 <redacted>
3   0x180cfde50 _os_once
4   0x180d06728 pthread_once
5   0x185a97960 <redacted>
6   0x185a971ac WebKitInitialize
7   0x186039f38 <redacted>
8   0x101509bb0 _dispatch_client_callout
9   0x10150aa28 dispatch_once_f
10  0x18070cfc8 <redacted>
11  0x1807138f8 <redacted>
12  0x18071ddb8 <redacted>
13  0x1003d8574 _TMaCSo9UIWebView
14  0x1003cd6cc _TFC6SwiftR7SignalRcfMS0_FT7baseUrlSS14connectionTypeOS_14ConnectionType12readyHandlerFS0_T__S0_
15  0x1003c79e4 _TFC6SwiftR7SignalRCfMS0_FT7baseUrlSS14connectionTypeOS_14ConnectionType12readyHandlerFS0_T__S0_
16  0x1003c78d4 _TZFC6SwiftR6SwiftR7connectfMS0_FTSS14connectionTypeOS_14ConnectionType12readyHandlerFCS_7SignalRT__GSqS2__
17  0x10014fbf8 _TZFC5Trade10Networking22startSignalRConnectionfMS0_FT_T_
18  0x1000f299c _TFFC5Trade19WatchViewController11viewDidLoadFS0_FT_T_U_FT_T_
19  0x1000c9b10 _TTRXFo__dT__XFdCb__dT__
20  0x101509bf0 _dispatch_call_block_and_release
21  0x101509bb0 _dispatch_client_callout
22  0x101518e10 _dispatch_root_queue_drain
23  0x1015184d8 _dispatch_worker_thread3
24  0x180d05470 _pthread_wqthread
25  0x180d05020 start_wqthread

is there something I'm doing wrong? Or there is no way of getting around this?'
thanks :)

crash at SwiftR.swift line 354

I hit a few crashes in my app using SwiftR today.
When the crash happened, I was not sending/receiving any messages, I was just playing around by taking pictures with Camera and displaying pictures in the app.

It crashed at the same place in SwiftR.swift line 354.
I was using version 0.8.1 when the crash happened,
then I used version 0.8.3,then it crashed again, but this time Crashlytics did not catch the crash, so I'm not 100% sure.

Below is the stack trace caught by Crashlytics:

Thread : Crashed: com.apple.main-thread
0 SwiftR 0x10252c184 SignalR.(userContentController(SignalR) -> (WKUserContentController, didReceiveScriptMessage : WKScriptMessage) -> ()).(closure #1) (SwiftR.swift:354)
1 WebKit 0x188cac148 std::1::__function::__func<-[WKWebView evaluateJavaScript:completionHandler:]::$_0, std::_1::allocator<-[WKWebView evaluateJavaScript:completionHandler:]::$0>, void (WebKit::WebSerializedScriptValue, WebKit::CallbackBase::Error)>::operator()(WebKit::WebSerializedScriptValue&&, WebKit::CallbackBase::Error&&) + 392
2 WebKit 0x188d66378 WebKit::GenericCallbackWebKit::WebSerializedScriptValue
::invalidate(WebKit::CallbackBase::Error) + 60
3 WebKit 0x188cbd418 void WebKit::invalidateCallbackMapWTF::RefPtr<WebKit::CallbackBase >(WTF::HashMap<unsigned long long, WTF::RefPtrWebKit::CallbackBase, WTF::IntHash, WTF::HashTraits, WTF::HashTraitsWTF::RefPtr<WebKit::CallbackBase > >&, WebKit::CallbackBase::Error) + 224
4 WebKit 0x188d55a74 WebKit::WebPageProxy::resetState(WebKit::WebPageProxy::ResetStateReason) + 460
5 WebKit 0x188d58468 WebKit::WebPageProxy::resetStateAfterProcessExited() + 192
6 WebKit 0x188d5e5a4 WebKit::WebPageProxy::processDidCrash() + 44
7 WebKit 0x188d94fc0 WebKit::WebProcessProxy::didClose(IPC::Connection_) + 264
8 JavaScriptCore 0x18509eabc WTF::RunLoop::performWork() + 444
9 JavaScriptCore 0x18509f0f4 WTF::RunLoop::performWork(void_) + 40
10 CoreFoundation 0x183748240 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION* + 24
11 CoreFoundation 0x1837474e4 __CFRunLoopDoSources0 + 264
12 CoreFoundation 0x183745594 __CFRunLoopRun + 712
13 CoreFoundation 0x1836712d4 CFRunLoopRunSpecific + 396
14 GraphicsServices 0x18ce876fc GSEventRunModal + 168
15 UIKit 0x188236fac UIApplicationMain + 1488

Using WKWebView does not work

Hi Adam, The connection does not succeed when using WKWebView instead of UIWebView. The log shows "Disconnected" right after "Start" is called (no matter how many times I try). I am using Swift 2.0 and I tried on simulator and also on multiple devices. The transport method is WebSockets (I also tried with Auto). Is this a known issue? Are you able to replicate it? Thanks.

Global hub and unsubscribe from one event

Would it be possible to create a global variable hub. And at any place of code to be able to subscribe for an event. When we create a separate connection with a server, and then subscribe to an event, it doesn't work.
Moreover, is it possible to unsubsribe from an individual event without unsubscribing from all the events at once and destroying the connection?

Javascript functions are not called

I call the following method in viewWillAppear method:

func startSignalRConnection() {
    SwiftR.connect(self.pusherURL) { connection in
        print("connection ID: ", connection.connectionID)
    }
}

but the app crashes before printing anything here, because in the method shouldHandleRequest(request: NSURLRequest) -> Bool the variable msg is an empty string and it cannot parse it as json. In order to diagnose the problem, I edited the method like this:

func shouldHandleRequest(request: NSURLRequest) -> Bool {
    if request.URL!.absoluteString.hasPrefix("swiftr://") {
        print(request.URL!.absoluteString)
        let id = (request.URL!.absoluteString as NSString).substringFromIndex(9)
        let msg = webView.stringByEvaluatingJavaScriptFromString("readMessage(\(id))")!
        let data = msg.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!

        //debug

        let msg2 = webView.stringByEvaluatingJavaScriptFromString("console.log(swiftR.foobar)")!

        print("here1")
        print(id)
        print("here2")
        print(msg2)
        print("here3")
        print(msg)

        //debug

        let json: AnyObject = try! NSJSONSerialization.JSONObjectWithData(data, options: [])

        processMessage(json)

        return false
    }

    return true
}

swiftR.foobar is a variable I declared in the SwiftR.js file:

window.swiftR = {
    connection: null,
    hubs: {},
    transport: 'auto',
    headers: {},
    foobar : 1234
};

the output to those logs is as follows:

here1
91bihm8e
here2
//empty line(empty string)
here3
//empty line

Is there something wrong with the way I'm calling the functions?

Will it work for IOS 9.2?

I am using this in ios9.2. I cant able to run the project. if it works in ios9.2. please give me suggestions to proceed further. Thank You...

Getting Error When Receiving A Message

Hello

When I receive a message, i get the following

2016-04-17 18:28:02.346 twicie[4724:1488530] Connection Error: {
column = 4521;
errorMessage = "WebSocket closed.";
line = 8;
source = {
};
sourceURL = "file:///var/containers/Bundle/Application/58436F8E-A7E3-442C-81E6-944631644DBD/twicie.app/jquery.signalr-2.1.1.min.js";
transport = webSockets;
}

Any Suggestions??

User Properties

On a SignalR Server, I have a property called User. This is used in Clients.User(userID).sendMessage(message);

How can I set this on the client using SwiftR.

I'm setting it as a QueryString in the connection as a work around for now.

Error In Connecting to my server

Hello

I have these parameters to connect my SignalR server
Server Address : http://myurl.com
Hub Proxy : TaxiTopHub
Query String: "user_type=client"

I configured my connection like this

hubConnection = SwiftR.connect("http://myurl.com") { [weak self] connection in
connection.queryString = ["user_type": "client"]
self?.simpleHub = connection.createHubProxy("TaxiTopHub")

but when I run my code I get this error :
SwiftR unable to process message 1i9k4s3y: Error Domain=WKErrorDomain Code=5 "JavaScript execution returned a result of an unsupported type" UserInfo={NSLocalizedDescription=JavaScript execution returned a result of an unsupported type}

Please help me if it's possible

How to connect to a remote server

I am not having any luck receiving the connected callback. I am sure its something I am doing. Any ideas?
var persistentConnection: SignalR!

    persistentConnection = SwiftR.connect("http://10.3.29.79/gameserver/", connectionType: .Persistent) { connection in
        connection.received = { data in
            print(data!)
        }
        connection.connected = { print("connected: \(connection.connectionID)") }
        connection.connectionSlow = { print("connectionSlow") }
        connection.reconnecting = { print("reconnecting") }
        connection.reconnected = { print("reconnected") }
        connection.disconnected = { print("disconnected") }
    }

    // Send data
    persistentConnection.send("Persistent Connection Test")

    return true

how do the install?

why is the installation so brief!? I can't run the project. I get a link error: "command error with exit code 1"
The installation step says to create a pod file!? why? I just want to run the project to see the code
anyway, I created a signalR pod which installed a whole project that doesn't build, run or anything!?
Why is the installation step so brief!?
Can you add a couple of lines of what we are trying achieve there?
since the project doesn't run by itself.
I added more description here: http://stackoverflow.com/questions/37308604/in-xcode-project-i-get-this-linker-command-error-with-exit-code-1

double byte strings are not handled correctly

Run the SwiftR iOS sample, for ASCII text, it works great with a browser client. But for double byte strings (e.g. Chinese characters), the browser client shows the strings correctly, but the iOS client does not handled correctly.

Repro 1:

Send from the browser client with some Chinese characters "你好“, the iOS cilent shows garbage string like this: `}

Repro 2:

Send from the browser client with some other Chinese characters "你好吗", the iOS client crashed with below error.

OnDisconnected e835293b-1df2-4b3d-b995-1d6a0d619ec3
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb) bt

  • thread #1: tid = 0x112228, 0x000000010021d474 libswiftCore.dylib`function signature specialization <Arg[0] = Exploded, Arg[1] = Exploded, Arg[2] = Dead, Arg[3] = Dead> of Swift._fatalErrorMessage (Swift.StaticString, Swift.StaticString, Swift.StaticString, Swift.UInt) -> () + 44, queue = 'com.apple.main-thread', stop reason = EXC_BREAKPOINT (code=1, subcode=0x10021d474)
    • frame #0: 0x000000010021d474 libswiftCore.dylib`function signature specialization <Arg[0] = Exploded, Arg[1] = Exploded, Arg[2] = Dead, Arg[3] = Dead> of Swift._fatalErrorMessage (Swift.StaticString, Swift.StaticString, Swift.StaticString, Swift.UInt) -> () + 44

      frame #1: 0x00000001000ed148 SwiftR`SwiftR.SignalR.shouldHandleRequest (request=0x0000000170009640, self=0x00000001700d9280)(ObjectiveC.NSURLRequest) -> Swift.Bool + 2328 at SwiftR.swift:128

      frame #2: 0x00000001000ef160 SwiftR`SwiftR.SignalR.webView (webView=0x000000013f5146b0, request=0x0000000170009640, navigationType=Other, self=0x00000001700d9280)(ObjectiveC.UIWebView, shouldStartLoadWithRequest : ObjectiveC.NSURLRequest, navigationType : C.UIWebViewNavigationType) -> Swift.Bool + 120 at SwiftR.swift:180

      frame #3: 0x00000001000ef200 SwiftR`@objc SwiftR.SignalR.webView (SwiftR.SignalR)(ObjectiveC.UIWebView, shouldStartLoadWithRequest : ObjectiveC.NSURLRequest, navigationType : C.UIWebViewNavigationType) -> Swift.Bool + 100 at SwiftR.swift:0

      frame #4: 0x000000018aa9a0ac UIKit`-[UIWebView webView:decidePolicyForNavigationAction:request:frame:decisionListener:] + 332

      frame #5: 0x0000000185e36100 CoreFoundation__invoking___ + 144 frame #6: 0x0000000185d322fc CoreFoundation-[NSInvocation invoke] + 296
      frame #7: 0x0000000185d36e30 CoreFoundation-[NSInvocation invokeWithTarget:] + 68 frame #8: 0x000000019559c898 WebKitLegacy-[_WebSafeForwarder forwardInvocation:] + 172
      frame #9: 0x0000000185e33f6c CoreFoundation___forwarding___ + 440 frame #10: 0x0000000185d36ccc CoreFoundation_CF_forwarding_prep_0 + 92
      frame #11: 0x0000000185e36100 CoreFoundation**invoking_** + 144 frame #12: 0x0000000185d322fc CoreFoundation-[NSInvocation invoke] + 296
      frame #13: 0x0000000194742efc WebCoreHandleDelegateSource(void*) + 120 frame #14: 0x0000000185de8240 CoreFoundationCFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 24
      frame #15: 0x0000000185de74e4 CoreFoundation__CFRunLoopDoSources0 + 264 frame #16: 0x0000000185de5594 CoreFoundation__CFRunLoopRun + 712
      frame #17: 0x0000000185d112d4 CoreFoundationCFRunLoopRunSpecific + 396 frame #18: 0x000000018f5276fc GraphicsServicesGSEventRunModal + 168
      frame #19: 0x000000018a8d6fac UIKitUIApplicationMain + 1488 frame #20: 0x000000010003d294 SwiftR iOS Demomain + 164 at AppDelegate.swift:12
      frame #21: 0x0000000197cdaa08 libdyld.dylib`start + 4

how to overcome: Error Domain=WKErrorDomain Code=5

I'm running this SignalR server in my PC:
https://github.com/adamhartford/SignalRDemo
and I am trying to hit it from my swift client:
https://github.com/adamhartford/SwiftR

but I get this error:
Starting...
SwiftR unable to process message 4eg2u0fw: Error Domain=WKErrorDomain Code=5 "JavaScript execution returned a result of an unsupported type" UserInfo={NSLocalizedDescription=JavaScript execution returned a result of an unsupported type}
Disconnected.

my version of signalR is properly set as:
public static var signalRVersion: SignalRVersion = .v2_2_0

I am pointing to my pc server name (abc) in the hub connection:
hubConnection = SwiftR.connect("http://abc:8080") { [weak self] connection in
and my server is running waiting for hits.

Invoke method doesn't work

Hi! I'm getting this error while debugging using Safari: "SyntaxError: Unexpected token ')'"

<!doctype html><html><head></head><body><script src='file:///Users/orlangur/Library/Developer/CoreSimulator/Devices/70F03748-4D1D-4F68-9FCB-6AFD1DBFA0DB/data/Containers/Data/Application/392AA7DA-1AC9-454E-951F-2295A433B4AF/tmp/jquery-2.1.3.min.js'></script><script src='file:///Users/orlangur/Library/Developer/CoreSimulator/Devices/70F03748-4D1D-4F68-9FCB-6AFD1DBFA0DB/data/Containers/Data/Application/392AA7DA-1AC9-454E-951F-2295A433B4AF/tmp/jquery.signalR-2.2.0.min'></script><script src='file:///Users/orlangur/Library/Developer/CoreSimulator/Devices/70F03748-4D1D-4F68-9FCB-6AFD1DBFA0DB/data/Containers/Data/Application/392AA7DA-1AC9-454E-951F-2295A433B4AF/tmp/SwiftR.js'></script>)</body></html>

That is because of this lines from lib:

let html = "<!doctype html><html><head></head><body>"
                + "\(jqueryInclude)\(signalRInclude)\(jsInclude))"
                + "</body></html>"

But my main issue that invoke method doesn't send messages. According server logs, I'm able to connect and disconnect, but not sending any requests. Here is my code:

SwiftR.connect("http://myDomain.com") { connection in
            connection.queryString = ["access_token": token]
            connection.connected = {
                self.hub?.invoke("getChats", arguments: nil, callback: { (result, error) -> () in
                       print("socket get chats: \(result) \(error)")
                })
            }
            self.hub = connection.createHubProxy("agenthub")
}

Thank you!

Failed to return after waiting for 10 seconds.

I have been trying SwiftR for a week. but when I ran the project I got nothing. In viewDidLoadMethod I have set this code

 SwiftR.connect("http://maisad-001-site1.btempurl.com/signalr/") { connection in
            let simpleHub = connection.createHubProxy("maisAdChatHub")
            print("HUBBBBB   \(simpleHub)")
                        SwiftR.startAll()
            print("HUBBBBB1   \(simpleHub)")
            // Event handler
            simpleHub.on("newMessage") { args in
//                let message = args!["0"] as! String
//                let detail = args!["1"] as! String
                print("Send Messageeeeeeeee")
                print("Response : \(args)")


                // Invoke server method
              //  simpleHub.invoke("sendSimple", arguments: ["Simple Test", "This is a simple message"])

                // Invoke server method and handle response
                simpleHub.invoke("sendmessage", arguments: ["Simple Test", "Room1" , "Usernamee" , "photo"]) { (result, error) in
                    if let e = error {
                        print("Error message: \(e)")
                    } else {
                        print("Success!")
                        if let r = result {
                            print("Result: \(r)")
                        }
                    }
                }

            }
        }
    }

I put a breakpoint at line number 7 where simpleHub.on("newMessage") is called am getting a message in console and it is

2016-02-02 15:04:33.131 CHATAPP[3089:374824] void SendDelegateMessage(NSInvocation *): delegate (webView:decidePolicyForNavigationAction:request:frame:decisionListener:) failed to return after waiting 10 seconds. main run loop mode: kCFRunLoopDefaultMode

No Idea whats's going wrong... Need help!!!

Converting existing Javascript SignalR to SwiftR

I have a JS implementation of SignalR that goes like this

hub = $.connection.thisHub;
$.connection.hub.start().done(function () {
  hub.server.register(true);
});

and I am having trouble converting it to the SignalR equivalent.
I have tried

SwiftR.connect(url) { (connection) in
      let complexHub = connection.createHubProxy("thisHub")
      complexHub.on("done") { (response) in

  }
}

with no success. Any ideas?

Hub.on handler is never called.

Hello, in my implementation the event names that I need to attach some code are dynamic. This means that I don't now the name of the event before I call the invoke method.

Calling the Hub.on method right before the invoke doesn't seem to be working. The only way to make it work is to call the "Hub.on" methods right after the creation of the hub and before the connection is open.

Any ideas on how to resolve the issue?

Connecting Users to Group

How do I connect a user to a Group? I didn't find a Documentation for it. is there any code available to do so???

Can't handle response

Hi,

I'm trying to connect to my server and i can't retrieve the response. I've used Charles on my Mac to see the server response. I can connect to the server, but can't handle response.

I use
connection.received = { data in print("data: \(data)") } but noting is displayed on Xcode debug console.

Thank you by advance

Hub Id

@adamhartford is it possible with SwiftR to get something like this hub.Id like in javascript connection.hub.Id ??? or I need to contact the server to create one like Context.ConnectionId ???
or anything else ??? I saw a connectionId property in your js file can I use that property to get a connectionId to send it to the server ???

SwiftR invoke error

SwiftR invoke error:, i am getting this message consistently... can you help me with this? why and when does this error occurs?

Connection is automatically closed when the App enter foreground from background

Run an App with SwiftR. SignalR connected successfully with WebSocket. Press iPhone's home button, the app enters background. The connection still holds, I can see the ping every 10 seconds in the WebSocket payload.

But after 3 minutes, when I click the App icon, the App enters into foreground, then the Websocket closes immediately. and it never reconnects again.

Please refer to attached screenshot of Fiddler trace.

image

How do i build SwiftR for Generic iOS Device scheme?

I am in need to use the SwiftR in my app for SignalR notifications. However, i can use SwiftR only in Simulator mode, if i try to run it on Device, it does not allow me to use the framework due to architecture difference. This forces me to build the SwiftR framework project for iOS devices. Again, this does not build as i do not have a developer profile that i can use and cannot build the framework with the distribution profile that i have as it would notify my organisation of using the profile for building a third party framework.

I cant install this

I try cocoapods and carthage but i cant install this to my project. Can you help me? What is wrong?

please help me about "Received method"

i have a problem with method receive message from server
i don't know why i alway received the msg like that: "{
A = (
);
H = ChatHub;
M = onUserDisconnected;
}"
help me!!!

SignalR Connection remains lingering

Hello, I noticed that the connections remain in memory after disconnecting, so I was wondering how does that affect performance and is there an easy way to delete the unused SignalR (connection) objects? Thanks!

exception in shouldHandleRequest

getting error ->

fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}: file /Library/Caches/com.apple.xbs/Sources/swiftlang_PONDEROSA/swiftlang_PONDEROSA-700.1.101.6/src/swift/stdlib/public/core/ErrorType.swift, line 50

in SwiftR.swift file

func shouldHandleRequest(request: NSURLRequest) -> Bool {
if request.URL!.absoluteString.hasPrefix("swiftr://") {
let id = (request.URL!.absoluteString as NSString).substringFromIndex(9)
let msg = webView.stringByEvaluatingJavaScriptFromString("readMessage((id))")!
let data = msg.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let json: AnyObject = try! NSJSONSerialization.JSONObjectWithData(data, options: []) <-- on this line
processMessage(json)
return false
}
return true
}

There was an error in invoking server method

This happened today and I am now unable to call a server method. When I invoke a server method I get this error in console

Error : {
    column = 4521;
    errorMessage = "There was an error invoking Hub method 'hub.UpdateSignalrId'.";
    line = 8;
    source = Exception;
    sourceURL = "file:///Users/user/Library/Developer/Xcode/DerivedData/FRIDGE-gdbmgdyqdjmagugcqlaviizcimmm/Build/Products/Debug-iphonesimulator/SwiftR.framework/jquery.signalR-2.2.0.min.js";
}

Error : {
    column = 4521;
    errorMessage = "There was an error invoking Hub method 'hub.sendmessagetogroup'.";
    line = 8;
    source = Exception;
    sourceURL = "file:///Users/user/Library/Developer/Xcode/DerivedData/FRIDGE-gdbmgdyqdjmagugcqlaviizcimmm/Build/Products/Debug-iphonesimulator/SwiftR.framework/jquery.signalR-2.2.0.min.js";
}

is this comes from SWIFTR ? or may be a backend error?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.