Skip to content

Commit ed88085

Browse files
author
Vladimir Kucherenko
committed
Update readme to reflect new changes
1 parent 9a94133 commit ed88085

File tree

1 file changed

+30
-26
lines changed

1 file changed

+30
-26
lines changed

README.md

Lines changed: 30 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -4,38 +4,42 @@
44
55
## Usage
66
```swift
7-
Bencode.decode(data: Data) throws -> Any
7+
Bencode.decode(data: Data) throws -> BencodeResult
88
```
9-
10-
Strings returned as `Data` according to [bencode specification](https://wiki.theory.org/BitTorrentSpecification#Bencoding).
11-
You need to explicitly convert them to `String` if this is what you expect:
12-
9+
### BencodeResult
1310
```swift
14-
let result = try! Bencode.decode(data: bencodedData) as! Data
15-
let decodedString = String(data: result, encoding: .utf8)
11+
BencodeResult.integer -> Int?
12+
BencodeResult.string -> String?
13+
BencodeResult.list -> [BencodeResult]?
14+
BencodeResult.dictionary -> [String: BencodeResult]?
15+
BencodeResult.hexString -> String? // hexadecimal representation of swift Data. Data(bytes: [0, 1, 127, 128, 255]) -> 00017f80ff
1616
```
17-
> ⚠️ Be careful with force unwrapping, everything on this page provided just as an example!
18-
19-
<br /><br />
2017

21-
#### Example of decoding torrent file
18+
### Decoding torrent file
2219
```swift
2320
import Bencode
2421

2522
let url: URL = <path to torrent file>
2623
let data = try! Data(contentsOf: url!)
2724

2825
do {
29-
let result = try Bencode.decode(data: data) as! [String: Any]
30-
31-
guard let announceData = result["announce"] as? Data else {
32-
// Torrent file doesen't have "announce" field hence invalid.
33-
}
34-
35-
if let announce = String(data: announceData, encoding: .utf8) {
36-
print(announce)
37-
}
38-
26+
let result = try Bencode.decode(data: data)
27+
28+
if let announce = result.dictionary?["announce"]?.string {
29+
print(announce)
30+
}
31+
32+
if let announceList = result.dictionary?["announce"]?.list {
33+
// announceList is [BencodeResult]
34+
for item in announceList {
35+
print(item.string!)
36+
}
37+
}
38+
39+
if let creationDate = result.dictionary?["creation date"]?.integer {
40+
print(creationDate)
41+
}
42+
3943
} catch BencodeDecodeError.invalidFormat {
4044

4145
} catch {
@@ -50,10 +54,10 @@ do {
5054
import PackageDescription
5155

5256
let package = Package(
53-
<...>
54-
dependencies: [
55-
.Package(url: "https://github.com/VFK/SwiftyBencode.git", majorVersion: 0, minor: 1),
56-
]
57-
<...>
57+
<...>
58+
dependencies: [
59+
.Package(url: "https://github.com/VFK/SwiftyBencode.git", majorVersion: 0, minor: 2)
60+
]
61+
<...>
5862
)
5963
```

0 commit comments

Comments
 (0)