Skip to content

Commit

Permalink
Feature/add documentation articles (#72)
Browse files Browse the repository at this point in the history
* feat: add Getting Started article.

Resolves: none.

* Update GettingStarted.md

* feat: add making first request article

Resolves: none.

* feat: add articles for download and upload requests

Resolves: none.

* feat: add web socket article

Resolves: none.

* feat: add monitoring reachability article

Resolves: none.

* fix: lint documentation

Resolves: none.
  • Loading branch information
loay-ashraf committed Jan 27, 2024
1 parent 3d54298 commit afb4c5d
Show file tree
Hide file tree
Showing 19 changed files with 879 additions and 10 deletions.
106 changes: 106 additions & 0 deletions Docs.docc/Articles/ConnectingToWebSocket.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
# Connecting To WebSocket Server

Connect to a web socket server with **RxNetworkKit**

## Overview

In this article we will walk you through on how to connect to a web socket server and how to send/receive messages.

### Creating a http client

In this section, you will create a ``HTTPClient`` using a ``Session``.

- First, go to *ViewController.swift* file.

- Second, create a ``HTTPClient`` using a ``Session`` in the `viewDidLoad` method as done below:

```swift
import UIKit
import RxSwift
import RxNetworkKit

class ViewController: UIViewController {

let disposeBag: DisposeBag = .init()

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let sessionConfiguration = SessionConfiguration.default
let session = Session(configuration: sessionConfiguration)
let requestInterceptor = RequestInterceptor()
let httpClient = HTTPClient(session: session, requestInterceptor: requestInterceptor)
}

}
```

- Now, you are ready to connect to a web socket server.

### Connecting to a websocket server

In this section, you will create a ``WebSocket`` and send/receive messages to/from the server.

- First, call the `HTTPClient.websocket` method and pass the server url, protocols and close handler as arguments.

- Second, Subscribe to the output `Observable`s and call `WebSocket.connect` method as done below:


```swift
import UIKit
import RxSwift
import RxNetworkKit

class ViewController: UIViewController {

let disposeBag: DisposeBag = .init()

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let sessionConfiguration = SessionConfiguration.default
let session = Session(configuration: sessionConfiguration)
let requestInterceptor = RequestInterceptor()
let httpClient = HTTPClient(session: session, requestInterceptor: requestInterceptor)
// Replace with your web socket server url
let webSocket: WebSocket<Model> = httpClient.webSocket(URL(string: "wss://example")!,
["ts1"],
.init(code: { _ in .normalClosure },
reason: { _ in nil }))
webSocket.text
.subscribe(onNext: { text in
// print incoming text message
print(text)
})
.disposed(by: disposeBag)
webSocket.data
.subscribe(onNext: { model in
// dump incoming data
dump(model)
})
.disposed(by: disposeBag)
webSocket.error
.subscribe(onNext: { error in
// print error description (if any)
print(error.localizedDescription)
})
.disposed(by: disposeBag)
webSocket.connect()
}

}
```

- Optionally, you can send messages to the server via the `WebSocket.send(_:)` method.

- That's it, you are connected to a web socket server and ready to send/receive messages.

- Tip: You can disconnect from the web socket server at any time by calling the `WebSocket.disconnect` method.

- Note: Connection to the web socket server is terminated when the ``WebSocket`` instance is deallocated.

- Warning: If you intend to make updates to the UI, you must use the `observe(on: MainScheduler.instance)` operator to avoid updating the UI on a background thread (which may lead to unexpected behavior or crashes).

## Conclusion

Now, you can use **RxNetworkKit** to connect to a web socket server.
119 changes: 119 additions & 0 deletions Docs.docc/Articles/GettingStarted.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
# Getting Started

Add **RxNetworkKit** and the essential networking code to your project.

## Overview

You can add RxNetworkKit to your project as a Swift Package via SPM.

You also need to create ``Session`` and ``RESTClient`` objects so you can start making requests.

### Adding RxNetworkKit to your project

In this section, you will be adding RxNetworkKit to your project via Swift Package Manager.

- First, open the dependencies tab of your project.

- Tap the *+* button.

- In the search bar to the top right corner, paste this url:

[https://github.com/loay-ashraf/RxNetworkKit](https://github.com/loay-ashraf/RxNetworkKit)

- Tap the *Add Package* button to the bottom right corner.

![Add package window is visible and RxNetworkKit package is selected.](article-getting-started-#1.png)

- Second, tap the *Add Package* button and wait for Xcode to resolve package graph.

![Xcode is resolving the package graph.](article-getting-started-#2.png)

- Now, your all set and can now use **RxNetworkKit** in your project.

![Xcode has finished resolving the package graph and RxNetworkKit can be used in the project.](article-getting-started-#3.png)

### Adding required networking code

In this section, you will be creating ``Session`` and ``RESTClient`` objects.

- First, add a new Swift file to your project and name it *RequestInterceptor.swift*.

- Second, add an import statement for **RxNetworkKit** to the top of the newly created file.

- Add a new class with the name `RequestInterceptor` that conforms to the ``HTTPRequestInterceptor`` protocol as done below:

```swift
import Foundation
import RxNetworkKit

class RequestInterceptor: HTTPRequestInterceptor {

func adapt(_ request: URLRequest, for session: URLSession) -> URLRequest {
return request
}

func retryMaxAttempts(_ request: URLRequest, for session: URLSession) -> Int {
return 5
}

func retryPolicy(_ request: URLRequest, for session: URLSession) -> HTTPRequestRetryPolicy {
return .constant(time: 5.0)
}

func shouldRetry(_ request: URLRequest, for session: URLSession, dueTo error: HTTPError) -> Bool {
return true
}

}
```

- Finally, add an import statement for **RxNetworkKit** in *ViewController.swift* file and create ``SessionConfiguration``, ``Session`` and ``RESTClient`` objects in the `viewDidLoad` method as done below:

```swift
import UIKit
import RxNetworkKit

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let sessionConfiguration = SessionConfiguration.default
let session = Session(configuration: sessionConfiguration)
let requestInterceptor = RequestInterceptor()
let restClient = RESTClient(session: session, requestInterceptor: requestInterceptor)
}

}
```

- Alternatively, you can override the default ``SessionConfiguration`` by creating your own instance and providing different property values as done below:

```swift
import UIKit
import RxNetworkKit

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let sessionConfiguration = SessionConfiguration(urlSessionConfiguration: .default)
sessionConfiguration.setUserAgentHeader = false
sessionConfiguration.setUserAgentHeader = false
let session = Session(configuration: sessionConfiguration)
let requestInterceptor = RequestInterceptor()
let restClient = RESTClient(session: session, requestInterceptor: requestInterceptor)
}

}
```

## Conclusion

Now you are one step away from making a request using **RxNetworkKit**.

In the next article, you will learn how to create a ``HTTPRequestRouter`` and a `Decodable` model and use them with ``RESTClient`` to make a request.

You can read the next article here:
- <doc:MakingFirstRequest>
120 changes: 120 additions & 0 deletions Docs.docc/Articles/MakingDownloadRequest.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
# Making Download Requests

Make download requests with **RxNetworkKit**

## Overview

In this article, we will walk you through on how to make download requests.

### Adding a download request router

In this section, you will be adding a ``HTTPDownloadRequestRouter``.

- First, add a new Swift file to your project and name it *DownloadRequestRouter.swift*.

- Second, add an import statement for **RxNetworkKit** to the top of the newly created file.

- Finally, add a new enumeration with the name `DownloadRequestRouter` that conforms to the ``HTTPDownloadRequestRouter`` protocol as done below:

```swift
import Foundation
import RxNetworkKit

enum DownloadRequestRouter: HTTPDownloadRequestRouter {

case `default`(url: URL)

var scheme: HTTPScheme {
.https
}

var domain: String {
""
}

var path: String {
""
}

var headers: [String : String] {
[:]
}

var parameters: [String : String]? {
nil
}

var url: URL? {
switch self {
case .default(let url):
return url
}
}

}
```

- Note: Download requests have `GET` http method set by default, so you don't have to specify it in the download request router.

### Making a download request

In this section, you will create a ``HTTPClient`` and use the ``HTTPDownloadRequestRouter`` you created in the previous section with it to make a download request.

- First, go to *ViewController.swift* file and create a ``HTTPClient`` using a ``Session`` in the `viewDidLoad` method

- Second, Create a `DownloadRequestRouter`.

- Call the `HTTPClient.download` method and pass the `DownloadRequestRouter` as an argument.

- Subscribe to the output `Observable` as done below:

```swift
import UIKit
import RxSwift
import RxNetworkKit

class ViewController: UIViewController {

let disposeBag: DisposeBag = .init()

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let sessionConfiguration = SessionConfiguration.default
let session = Session(configuration: sessionConfiguration)
let requestInterceptor = RequestInterceptor()
let httpClient = HTTPClient(session: session, requestInterceptor: requestInterceptor)
// Replace with your download url
let downloadRequestRouter = DownloadRequestRouter.default(url: URL(string: "https://example.com/image/2435454.png")!)
httpClient.download(downloadRequestRouter)
.subscribe(onNext: { event in
switch event {
case .progress(let progress):
// print download progress
print("Downloading: \(progress.fractionCompleted)%")
case .completedWithData(data: let data):
// dump the received file data
dump(data)
default: break
}
}, onError: { error in
// print the error description (if any)
print(error.localizedDescription)
})
.disposed(by: disposeBag)
}

}
```

- That's it, you made a download request.

- Tip: If you need to save the downloaded file to the disk, you can provide the save location url through the `fileURL` parameter.

- Note: If you choose to save the downloaded file to the disk, you will receive the `completed` download event instead of the `completedWithData` download event.

- Warning: If you intend to make updates to the UI, you must use the `observe(on: MainScheduler.instance)` operator to avoid updating the UI on a background thread (which may lead to unexpected behavior or crashes).

## Conclusion

Now, you can use **RxNetworkKit** to make download requests.
Loading

0 comments on commit afb4c5d

Please sign in to comment.