File tree 3 files changed +57
-0
lines changed
Sources/BasedUtils/extensions
3 files changed +57
-0
lines changed Original file line number Diff line number Diff line change @@ -60,7 +60,15 @@ BasedUtils.shortenAddress(address1) // "0xd8dA...6045"
60
60
61
61
### Extensions
62
62
63
+ Data
64
+
65
+ ``` swift
66
+ let data = " https://example.com" .data (using : .utf8 )!
67
+ data.base64UrlEncode () // "aHR0cHM6Ly9leGFtcGxlLmNvbQ"
68
+ ```
69
+
63
70
String
71
+
64
72
``` swift
65
73
let address = " 0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
66
74
let hash = " d8dA6B"
Original file line number Diff line number Diff line change
1
+ //
2
+ // Data.swift
3
+ //
4
+ //
5
+ // Created by Jann Driessen on 24.06.24.
6
+ //
7
+
8
+ import Foundation
9
+
10
+ public extension Data {
11
+
12
+ func base64UrlEncode( ) -> String {
13
+ var base64String = self . base64EncodedString ( )
14
+ // Replace standard Base64 characters to make it URL-safe
15
+ base64String = base64String
16
+ . replacingOccurrences ( of: " + " , with: " - " )
17
+ . replacingOccurrences ( of: " / " , with: " _ " )
18
+ . replacingOccurrences ( of: " = " , with: " " )
19
+ return base64String
20
+ }
21
+
22
+ }
23
+
Original file line number Diff line number Diff line change
1
+ //
2
+ // DataExtensionsTests.swift
3
+ //
4
+ //
5
+ // Created by Jann Driessen on 24.06.24.
6
+ //
7
+
8
+ import XCTest
9
+ @testable import BasedUtils
10
+
11
+ final class DataExtensionsTests : XCTestCase {
12
+
13
+ func testBase64UrlEncode( ) throws {
14
+ let basicEncoding = " https://example.com " . data ( using: . utf8) !
15
+ let urlWithQueryParams = " https://example.com/path?query=parameter " . data ( using: . utf8) !
16
+ let urlWithSpecialCharacters = " https://example.com/path?query=param+eter&foo=bar/baz " . data ( using: . utf8) !
17
+ let simpleText = " Hello world " . data ( using: . utf8) !
18
+ let emptyString = " " . data ( using: . utf8) !
19
+ XCTAssertEqual ( basicEncoding. base64UrlEncode ( ) , " aHR0cHM6Ly9leGFtcGxlLmNvbQ " )
20
+ XCTAssertEqual ( urlWithQueryParams. base64UrlEncode ( ) , " aHR0cHM6Ly9leGFtcGxlLmNvbS9wYXRoP3F1ZXJ5PXBhcmFtZXRlcg " )
21
+ XCTAssertEqual ( urlWithSpecialCharacters. base64UrlEncode ( ) , " aHR0cHM6Ly9leGFtcGxlLmNvbS9wYXRoP3F1ZXJ5PXBhcmFtK2V0ZXImZm9vPWJhci9iYXo " )
22
+ XCTAssertEqual ( simpleText. base64UrlEncode ( ) , " SGVsbG8gd29ybGQ " )
23
+ XCTAssertEqual ( emptyString. base64UrlEncode ( ) , " " )
24
+ }
25
+
26
+ }
You can’t perform that action at this time.
0 commit comments