Coder Social home page Coder Social logo

launchdarkly / swift-eventsource Goto Github PK

View Code? Open in Web Editor NEW
184.0 39.0 34.0 1.1 MB

Server-sent events (SSE) client implementation in Swift for iOS, macOS, tvOS, and watchOS

Home Page: https://launchdarkly.github.io/swift-eventsource/

License: Other

Swift 97.41% Ruby 1.05% C 0.22% Makefile 1.32%
launchdarkly launchdarkly-sdk-component swift ios eventsource server-sent-events macos tvos watchos managed-by-terraform

swift-eventsource's Introduction

LDSwiftEventSource

Run CI CocoaPods Carthage compatible SwiftPM compatible Platform

LDSwiftEventSource is a cross platform implementation of the EventSource specification written in Swift. It was developed for use in the LaunchDarkly iOS SDK. Generated API docs are available on GitHub Pages.

Requirements

  • iOS 11.0+ / watchOS 4.0+ / tvOS 11.0+ / macOS 10.13+
  • Swift 5.1+

Installation

CocoaPods

To use the CocoaPods dependency manager to integrate LDSwiftEventSource into your Xcode project, specify it in your Podfile:

pod 'LDSwiftEventSource', '~> 3.3'

Carthage

To use the Carthage dependency manager to integrate LDSwiftEventSource into your Xcode project, specify it in your Cartfile:

github "LaunchDarkly/swift-eventsource" ~> 3.3

Swift Package Manager

The Swift Package Manager is a dependency manager integrated into the swift compiler and Xcode. Note that the LDSwiftEventSource Swift package provides both a LDSwiftEventSource product, which is explicitly dynamic, and a LDSwiftEventSourceStatic product which is explicitly static.

To integrate LDSwiftEventSource into an Xcode project, go to the project editor, and select Swift Packages. From here hit the + button and follow the prompts using https://github.com/LaunchDarkly/swift-eventsource.git as the URL.

To include LDSwiftEventSource in a Swift package, simply add it to the dependencies section of your Package.swift file. And add the desired product as a dependency for your targets.

dependencies: [
    .package(url: "https://github.com/LaunchDarkly/swift-eventsource.git", .upToNextMajor(from: "3.3.0"))
]

Contributing

We encourage pull requests and other contributions from the community. Check out our contributing guidelines for instructions on how to contribute to this SDK.

About LaunchDarkly

  • LaunchDarkly is a continuous delivery platform that provides feature flags as a service and allows developers to iterate quickly and safely. We allow you to easily flag your features and manage them from the LaunchDarkly dashboard. With LaunchDarkly, you can:
    • Roll out a new feature to a subset of your users (like a group of users who opt-in to a beta tester group), gathering feedback and bug reports from real-world use cases.
    • Gradually roll out a feature to an increasing percentage of users, and track the effect that the feature has on key metrics (for instance, how likely is a user to complete a purchase if they have feature A versus feature B?).
    • Turn off a feature that you realize is causing performance problems in production, without needing to re-deploy, or even restart the application with a changed configuration file.
    • Grant access to certain features based on user attributes, like payment plan (eg: users on the ‘gold’ plan get access to more features than users in the ‘silver’ plan). Disable parts of your application to facilitate maintenance, without taking everything offline.
  • LaunchDarkly provides feature flag SDKs for a wide variety of languages and technologies. Check out our documentation for a complete list.
  • Explore LaunchDarkly

swift-eventsource's People

Contributors

apache-hb avatar brianmichel avatar bwoskow-ld avatar g-mark avatar github-actions[bot] avatar gwhelanld avatar keelerm84 avatar kparkinson-ld avatar ld-repository-standards[bot] avatar simba909 avatar tanderson-ld avatar tomasf 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swift-eventsource's Issues

Add a way to disable logging

Is your feature request related to a problem? Please describe.

Yes. The logging of the LaunchDarkly iOS Client is verbose. When debugging, it is not uncommon to get hundreds of debugging statement in the console, with no easy to disable them.

Describe the solution you'd like

Create a way to disable logging, and optionally have the LaunchDarkly iOS Client configure it to match. Ideally somethings like:

Logs.logger = .disabled

Describe alternatives you've considered

  • Swizzling the Logs class, but since it is not an objective-c class, it cannot be swizzled
  • Forking the library, and replacing the logging code with noop implementations

Additional context

Not that I can see.

一直重连,怎么中断?

`// Tells the delegate that the task finished transferring data.
public func urlSession(_ session: URLSession,
task: URLSessionTask,
didCompleteWithError error: Error?) {
utf8LineParser.closeAndReset()
let currentRetry = eventParser.reset()

    guard readyState != .shutdown
    else { return }

    if let error = error {
        if (error as NSError).code != NSURLErrorCancelled {
            logger.log(.info, "Connection error: %@", error.localizedDescription)
            if dispatchError(error: error) == .shutdown {
                logger.log(.info, "Connection has been explicitly shut down by error handler")
                if readyState == .open {
                    config.handler.onClosed()
                }
                readyState = .shutdown
                return
            }
        }
    } else {
        logger.log(.info, "Connection unexpectedly closed.")
    }

    if readyState == .open {
        config.handler.onClosed()
    }

    readyState = .closed
    let sleep = reconnectionTimer.reconnectDelay(baseDelay: currentRetry)
    // this formatting shenanigans is to workaround String not implementing CVarArg on Swift<5.4 on Linux
    logger.log(.info, "Waiting %@ seconds before reconnecting...", String(format: "%.3f", sleep))
    delegateQueue.asyncAfter(deadline: .now() + sleep) { [weak self] in
        self?.connect()
    }
}`

这个方法在 readyState = .closed 之后,为什么有 sleep 后重新连接的逻辑,如何设置可以终止呢?

Connection Error 🐛

Describe the bug

Hello thanks for great library 🙌.
I'm trying to build wrapper library using LDSwiftEventSource internally on my react-native app.
However, I'm having problem with getting any events from server.

Logs are attached as screen shots below.

My questions are

  1. Is this library issue or am I doing anything wrong?
  2. Can I get callback for error below?

To reproduce
Here's my minimal code

import LDSwiftEventSource

@objc(EventSource)
class EventSource: NSObject {
    private var connceted = false;
    
    @objc(connect:options:)
    func connect(url: String, options: NSObject) -> Void {
        print(url, options, self.connceted);
        
        let handlers = MyEventHandler()
        
        guard let url = URL(string: url) else {
            fatalError("Invalid URL")
        }
        
        var config = LDSwiftEventSource.EventSource.Config(handler: handlers, url: url);
        
        config.connectionErrorHandler = self.connectionErrorHandler
        
        config.method = "GET"
        
        config.headers = ["Authorization": "REQUIRED TOKEN", "Content-Type": "application/json", "Accept": "text/event-source"]
        
        var instance = LDSwiftEventSource.EventSource(config: config);
        
        instance.start();
        
        self.connceted = true;
        
        print("started instance")
    }
    
    @objc(disconnect)
    func disconnect() -> Void {
        print("disconnected")
    }
    
    func connectionErrorHandler(error: Error) -> LDSwiftEventSource.ConnectionErrorAction {
        print("RNES error", error)
        guard let unsuccessfulResponseError = error as? UnsuccessfulResponseError else { return .proceed }
        
        let responseCode: Int = unsuccessfulResponseError.responseCode
        if 204 == responseCode {
            return .shutdown
        }
        return .proceed
    }
}

public class MyEventHandler: LDSwiftEventSource.EventHandler {
    public func onOpened() {
        print("RNES Connection opened")
    }
    
    public func onClosed() {
        print("RNES Connection closed")
    }
    
    public func onMessage(eventType: String, messageEvent: MessageEvent) {
        print("RNES Received event of type \(eventType) with data \(messageEvent)")
    }
    
    public func onComment(comment: String) {
        print("RNES Received comment: \(comment)")
    }
    
    public func onError(error: Error) {
        print("RNES Error occurred: \(error)")
    }
}

Expected behavior
I'm expecting to get any data from server.
I'm mocking local server with express using ngrok to test on real device.
But I can't get any request from client on my server console.
I'm using same server code and works fine on browser & android.

Logs

Here's my logs.

Screenshot 2023-09-13 at 3 43 55 PM

Library version
"LDSwiftEventSource": "3.1.1"

XCode and Swift version
XCode 14.3.1, Swift 5.8.1

Platform the issue occurs on
Testing on iPhone real device & iPhone simulator.

Enable dynamic linking in SPM

Is your feature request related to a problem? Please describe.

Xcode 12.5 (now in Beta) can resolve packages without specified type as dynamic and therefore resolve an issue with statically linked dependencies in multiple targets (app, extension, …).

But this library defines the static type of package LDSwiftEventSourceStatic. And so Xcode is not able to resolve dependencies successfully.

Swift package product 'LDSwiftEventSourceStatic' is linked as a static library by 'app' and 'extension'. This will result in duplication of library code.

Describe the solution you'd like

Keep package type empty or use dynamic.

Why does the delegate reconnect even if there is no error?

The open method is called and the response is returned successfully, but then the following function is called (and so the onMessage is not reached)

public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)

The error is nil, so it reconnects and keeps re-calling the API even if the API is successful. Is it a bug?

Get response data when the status is not in 200-300

I used this package to access the OpenAI API. However, when the response has a status code outside of the range 200-300, an error occurs. The UnsuccessfulResponseError object only includes a responseStatus field, but OpenAI responded with a JSON error message like the following:

{
  "error": {
    "param": null,
    "message": "Rate limit reached for default-gpt-3.5-turbo in organization org-xxx on requests per minute. Limit: 20 / min. Current: 30 / min. Contact [email protected] if you continue to have issues. Please add a payment method to your account to increase your rate limit. Visit https:\/\/platform.openai.com\/account\/billing to add a payment method.",
    "code": null,
    "type": "requests"
  }
}

I would like to retrieve the message from this error response, but I couldn't find a way to do it. Is it possible to do so with the current version? If not, could you please add this functionality in a future release?

Build failures with cycle: LDSwiftEventSource

Is this a support request?
This issue tracker is maintained by LaunchDarkly SDK developers and is intended for feedback on the SDK code. If you're not sure whether the problem you are having is specifically related to the SDK, or to the LaunchDarkly service overall, it may be more appropriate to contact the LaunchDarkly support team; they can help to investigate the problem and will consult the SDK team if necessary. You can submit a support request by going here or by emailing [email protected].

Note that issues filed on this issue tracker are publicly accessible. Do not provide any private account information on your issues. If your problem is specific to your account, you should submit a support request as described above.

Describe the bug
After some builds, we get an error building our app.

❌ error: Cycle inside LDSwiftEventSource; building could produce unreliable results.

Removing the pods directory, and rebuilding tends to fix the issue. However, this happens frequently on CI. Removing the pods directory, and reinstalling pods is a lengthy process which would slow down our CI.

Any ideas
To reproduce
Include this library, and build app. After a few dozen attempts, the build will start failing

Expected behavior
Build shouldn't fail

Logs
If applicable, add any log output related to your problem.

SDK version
The version of this SDK that you are using.

  • LaunchDarkly (5.4.0):
    • LaunchDarkly/Core (= 5.4.0)
  • LaunchDarkly/Core (5.4.0):
    • LDSwiftEventSource (= 1.2.1)
  • LaunchdarklyReactNativeClient (4.0.0):
    • LaunchDarkly (= 5.4.0)
    • React
      Language version, developer tools
      XCode 12.4

OS/platform

Additional context
Add any other context about the problem here.

crash in append when awakening from background

Describe the bug
My app is configured to disconnect from the event source when backgrounded. When it comes back up, I think there can sometimes be a residual callback pending that tries to get processed but everything has been shut down.

To reproduce
Dang good question, I haven't been able to isolate it, but it happens occasionally when I re-foreground my app.

Expected behavior
no crash

Logs
This is what I get from the crash log. I have no idea how to make it symbolify it properly. If you have any hints on that, I would appreciate it.

Thread 5 name:  Dispatch queue: com.apple.NSURLSession-delegate
Thread 5 Crashed:
0   libsystem_kernel.dylib        	0x00000001bb37495c __pthread_kill + 8
1   libsystem_pthread.dylib       	0x00000001d62c79e8 pthread_kill + 212
2   libsystem_c.dylib             	0x00000001996bf934 abort + 100
3   libsystem_malloc.dylib        	0x000000019f389030 _malloc_put + 0
4   libsystem_malloc.dylib        	0x000000019f3892a4 malloc_zone_error + 100
5   libsystem_malloc.dylib        	0x000000019f377558 free_small_botch + 36
6   libswiftCore.dylib            	0x0000000194725714 _swift_release_dealloc + 28
7   libswiftCore.dylib            	0x00000001945d1d4c _StringGuts.prepareForAppendInPlace+ 1748300 (totalCount:otherUTF8Count:) + 388
8   libswiftCore.dylib            	0x00000001945d1ec0 _StringGuts.append+ 1748672 (_:) + 220
9   libswiftCore.dylib            	0x0000000194571730 _StringGuts.append+ 1353520 (_:) + 88
10  LDSwiftEventSource            	0x0000000104a1a6fc 0x104a0c000 + 59132
11  LDSwiftEventSource            	0x0000000104a18998 0x104a0c000 + 51608
12  LDSwiftEventSource            	0x0000000104a166a4 0x104a0c000 + 42660
13  CFNetwork                     	0x000000019120d838 0x191047000 + 1861688
14  libdispatch.dylib             	0x00000001906ad298 _dispatch_call_block_and_release + 24
15  libdispatch.dylib             	0x00000001906ae280 _dispatch_client_callout + 16
16  libdispatch.dylib             	0x000000019068a4fc _dispatch_lane_serial_drain$VARIANT$armv81 + 568
17  libdispatch.dylib             	0x000000019068b01c _dispatch_lane_invoke$VARIANT$armv81 + 456
18  libdispatch.dylib             	0x0000000190694808 _dispatch_workloop_worker_thread + 692
19  libsystem_pthread.dylib       	0x00000001d62c85a4 _pthread_wqthread + 272
20  libsystem_pthread.dylib       	0x00000001d62cb874 start_wqthread + 8

Library version
1.1.0, but I compared against the 1.2.0 and it appears this part of the code hasn't changed.

XCode and Swift version
XCode 12.1, Swift 5.1

Platform the issue occurs on
iPhone

Additional context
I realize this isn't a lot to go on, but I'm not sure how to debug it further, I'm reasonably new to swift. The code is being called through a Capacitor plugin I wrote so there's some wiggle room in timing between the javascript layer making things happen and that finally getting down to the swift/native layer.

Can provide a simple example of use this repo?

Is your feature request related to a problem? Please describe.
Recent I am try to use Event Source in my project, when I search on Github, only this repo is really perfect.
But I am new to iOS, I use many time try to use it in my project, try to under the LaunchDarkly SDK and other user project, but still under stand, and my project still can't work.
Can this repo provide simple example use in iOS or Mac project?
I already try in my ContentView, but really no response.

let es = EventSource(config: config)
es.start()

Describe the solution you'd like
Provide a simple project use this excellent repo.

Additional context
Thanks for upload this project in Github.

Cannot start app after build

Describe the bug
The app builds without any Problems and also installs on my phone, but as soon as I start it from Xcode, this error pops up (Logs section). When I install onto an Simulator, it runs fine, but as soon as I run it standalone, the app crashes with the same error that the Library couldn't be found.

To reproduce
Import the Library into SwiftPackageManager and try running the app.

Expected behavior
The app should start without any problems.

Logs
dyld[5161]: Library not loaded: @rpath/LDSwiftEventSource.framework/LDSwiftEventSource Referenced from: <A8122676-3D07-3978-B99B-457DD136A6EC> /private/var/containers/Bundle/Application/94AE1A3D-0930-4205-9CAA-C6DD28758505/Em4D.app/Em4D Reason: tried: '/private/var/containers/Bundle/Application/94AE1A3D-0930-4205-9CAA-C6DD28758505/Em4D.app/Frameworks/LDSwiftEventSource.framework/LDSwiftEventSource' (no such file), '/private/var/containers/Bundle/Application/94AE1A3D-0930-4205-9CAA-C6DD28758505/Em4D.app/Frameworks/LDSwiftEventSource.framework/LDSwiftEventSource' (no such file), '/private/preboot/Cryptexes/OS@rpath/LDSwiftEventSource.framework/LDSwiftEventSource' (no such file), '/private/var/containers/Bundle/Application/94AE1A3D-0930-4205-9CAA-C6DD28758505/Em4D.app/Frameworks/LDSwiftEventSource.framework/LDSwiftEventSource' (no such file), '/private/var/containers/Bundle/Application/94AE1A3D-0930-4205-9CAA-C6DD28758505/Em4D.app/Frameworks/LDSwiftEventSource.framework/LDSwiftEventSource' (no such file), '/System/Library/Frameworks/LDSwiftEventSource.framework/LDSwiftEventSource' (no such file, not in dyld cache) Library not loaded: @rpath/LDSwiftEventSource.framework/LDSwiftEventSource Referenced from: <A8122676-3D07-3978-B99B-457DD136A6EC> /private/var/containers/Bundle/Application/94AE1A3D-0930-4205-9CAA-C6DD28758505/Em4D.app/Em4D Reason: tried: '/private/var/containers/Bundle/Application/94AE1A3D-0930-4205-9CAA-C6DD28758505/Em4D.app/Frameworks/LDSwiftEventSource.framework/LDSwiftEventSource' (no such file), '/private/var/containers/Bundle/Application/94AE1A3D-0930-4205-9CAA-C6DD28758505/Em4D.app/Frameworks/LDSwiftEventSource.framework/LDSwiftEventSource' (no such file), '/private/preboot/Cryptexes/OS@rpath/LDSwiftEventSource.framework/LDSwiftEventSource' (no such file), '/private/var/containers/Bundle/Application/94AE1A3D-0930-4205-9CAA-C6DD28758505/Em4D.app/Frameworks/LDSwiftEventSource.framework/LDSwiftEventSource' (no such file), '/private/var/containers/Bundle/Application/94AE1A3D-0930-4205-9CAA-C6DD28758505/Em4D.app/Frameworks/LDSwiftEventSource.framework/LDSwiftEventSource' (no such file), '/System/Libr dyld config: DYLD_LIBRARY_PATH=/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/Developer/usr/lib/libBacktraceRecording.dylib:/Developer/usr/lib/libMainThreadChecker.dylib:/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib

Library version
1.3.1

XCode and Swift version
Xcode 13.4.1, Swift 5.6.1, IOS 16 beta and 15.5

Platform the issue occurs on
iPhone

Additional context
Add any other context about the problem here.

[Feat Request] Read response data on error

Is your feature request related to a problem? Please describe.

I trying to read response data (json error message from server) when request error occurred while creating connection.
But only responseCode is available for UnsuccessfulResponseError.

Describe the solution you'd like

as-is

public class UnsuccessfulResponseError: Error {
    /// The HTTP response code received.
    public let responseCode: Int

    /**
     Constructor for an `UnsuccessfulResponseError`.

     - Parameter responseCode: The HTTP response code of the unsuccessful response.
     */
    public init(responseCode: Int) {
        self.responseCode = responseCode
    }
}

to-be

public class UnsuccessfulResponseError: Error {
    /// The HTTP response code received.
    public let responseCode: Int

    public let data: Data?
    public let response: Response?
    public let error: Error?
}

Can UnsuccessfulResponseError be like this?

I'm newbie learning swift and I tried to solve this by myself but failed to do so

#65

Describe alternatives you've considered

Additional context

[LDEventSource] Connection unexpectedly closed.

Describe the bug
[LDEventSource] Connection unexpectedly closed.

To reproduce

my code

import Foundation

import LDSwiftEventSource



class MyHandler: EventHandler {
    func onOpened() {
        print("MyHandler onOpened")
    }
    
    func onClosed() {
        print("MyHandler onClosed")
    }
    
    func onMessage(eventType: String, messageEvent: MessageEvent) {
        print("MyHandler eventType:\(eventType),messageEvent:\(messageEvent.data)")
    }
    
    func onComment(comment: String) {
        print("MyHandler onComment:\(comment)")
    }
    
    func onError(error: Error) {
        print("MyHandler onError:\(error)")
    }
}



class EssayStream {
    var eventSource: EventSource?
    
    
    func GenerateEssayStream2(words:[String]) {
        
        let essayReq = EssayReq(words: words)
        
        guard let sseURL = URL(string: "http://127.0.0.1:8888/v1/word/generate_essay_stream") else {
                print("Invalid SSE URL")
                return
            }
        
        
        let myHandler = MyHandler()

        var config = EventSource.Config(handler: myHandler, url: sseURL)
        config.method = "POST"
        config.headers["Content-Type"] = "application/json"
        
        do {
            let jsonData = try JSONEncoder().encode(essayReq)
            config.body = jsonData
        } catch {
            print("Error encoding request data: \(error)")
            return
        }
        self.eventSource = EventSource(config: config)

        self.eventSource?.start()

    }

}

I noticed the error: Connection unexpectedly closed. but when I captured the packages, I saw a complete request and response
net.csv

Expected behavior
Print the content of each event from server side
func onMessage(eventType: String, messageEvent: MessageEvent) {
print("MyHandler eventType:(eventType),messageEvent:(messageEvent.data)")
}

Logs

2023-10-05 14:53:22.588493+0800 sweet[16290:10957563] [LDEventSource] State: raw -> connecting
2023-10-05 14:53:22.589071+0800 sweet[16290:10957563] [LDEventSource] Starting EventSource client
2023-10-05 14:53:23.428033+0800 sweet[16290:10957643] [LDEventSource] Initial reply received
2023-10-05 14:53:23.428219+0800 sweet[16290:10957643] [LDEventSource] State: connecting -> open
MyHandler onOpened
2023-10-05 14:53:27.133741+0800 sweet[16290:10957563] [LDEventSource] Connection unexpectedly closed.
MyHandler onClosed
2023-10-05 14:53:27.133974+0800 sweet[16290:10957563] [LDEventSource] State: open -> closed
2023-10-05 14:53:27.134163+0800 sweet[16290:10957563] [LDEventSource] Waiting 1.957 seconds before reconnecting...
2023-10-05 14:53:29.220017+0800 sweet[16290:10957553] [LDEventSource] Starting EventSource client
2023-10-05 14:53:29.919622+0800 sweet[16290:10957643] [LDEventSource] Initial reply received
2023-10-05 14:53:29.919780+0800 sweet[16290:10957643] [LDEventSource] State: closed -> open
MyHandler onOpened

Library version
3.1.1
XCode and Swift version
For instance, XCode 14.3.1

Platform the issue occurs on
iPhone

Additional context

Should not reconnect, when 204 received

Describe the bug
According to SSE specification (here) client should not try to reconnect, when response with 204 http code is received. In this implementation all 2xx codes are treated as success. So when 204 is received and then connection is closed, the library tries to reconnect.

To reproduce
Send initial response with 204 code.

Expected behavior
Library should not try to reconnect. It should shutdown instead. Also application should be notified, that this happen.

XCode and Swift version
For instance, XCode 11.5, Swift 5.1.

Platform the issue occurs on
iPhone

Calling .stop() does not end the request. The request is still open against the server.

Is this a support request? Yes

Describe the bug
calling .stop() does not kill the request. If I call .stop() on an event source, I would expect the http request to close. My use case is creating an SSE connection and then close it and create a new one in specific scenarios. This is not working (maybe by design?).
To reproduce
Steps to reproduce the behavior.
Create many requests but check if an eventsource already exists and call .stop() on it and create a new one.
Expected behavior
A clear and concise description of what you expected to happen.
The "old" event source http requests to send a connection: close to the server and close.

Logs
If applicable, add any log output related to your problem.

SDK version
The version of this SDK that you are using.
LDSwiftEventSource (1.2.1)
Language version, developer tools
For instance, Go 1.11 or Ruby 2.5.3. If you are using a language that requires a separate compiler, such as C, please include the name and version of the compiler too.
Swift5
OS/platform
For instance, Ubuntu 16.04, Windows 10, or Android 4.0.3. If your code is running in a browser, please also include the browser type and version.
iOS14.5

Please add a small example how to use this.

Hello,

Thank you first for this amazing project. I'm desperately looking for a SSE library in Swift.
I have difficulties understanding how to utilise this library in Swift. There is an API doc, but still very difficult to understand where to get started. A simple example would be amazing.

     guard let urlFull = URL(string: Constants.apiServiceUrlFull) else {
         print("Invalid Full URL")
         return
    }
        var request = URLRequest(url: urlFull)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
   
        let requestBody: [String: Any] = [
            "max_new_tokens": 256,
            "max_tokens": 256,
            "stream": true,
        ]

        do {
            let jsonData = try JSONSerialization.data(withJSONObject: requestBody, options: [])
            request.httpBody = jsonData
        } catch {
            print("Error serializing JSON: \(error)")
            return
        }

For example if I had this POST that requires Streaming as response, how would I use your library please?

Thanks

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.