|
4 | 4 |
|
5 | 5 | ## Usage |
6 | 6 | ```swift |
7 | | -Bencode.decode(data: Data) throws -> Any |
| 7 | +Bencode.decode(data: Data) throws -> BencodeResult |
8 | 8 | ``` |
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 |
13 | 10 | ```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 |
16 | 16 | ``` |
17 | | -> ⚠️ Be careful with force unwrapping, everything on this page provided just as an example! |
18 | | -
|
19 | | -<br /><br /> |
20 | 17 |
|
21 | | -#### Example of decoding torrent file |
| 18 | +### Decoding torrent file |
22 | 19 | ```swift |
23 | 20 | import Bencode |
24 | 21 |
|
25 | 22 | let url: URL = <path to torrent file> |
26 | 23 | let data = try! Data(contentsOf: url!) |
27 | 24 |
|
28 | 25 | 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 | + |
39 | 43 | } catch BencodeDecodeError.invalidFormat { |
40 | 44 |
|
41 | 45 | } catch { |
|
50 | 54 | import PackageDescription |
51 | 55 |
|
52 | 56 | 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 | +<...> |
58 | 62 | ) |
59 | 63 | ``` |
0 commit comments