/SwiftyBencode

A general purpose bencode decoder written in Swift 3

Primary LanguageSwiftMIT LicenseMIT

SwiftyBencode GitHub release Build Status

A general purpose bencode decoder written in Swift 3

Usage

Bencode.decode(data: Data) throws -> BencodeResult

BencodeResult

BencodeResult.integer -> Int?
BencodeResult.string -> String?
BencodeResult.list -> [BencodeResult]?
BencodeResult.dictionary -> [String: BencodeResult]?

// hexadecimal representation of swift Data.
BencodeResult.hexString -> String? // Data(bytes: [0, 1, 127, 128, 255]) -> 00017f80ff

Decoding torrent file

import Bencode

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

do {
  let result = try Bencode.decode(data: data)

  if let announce = result.dictionary?["announce"]?.string {
    print(announce)
  }

  if let announceList = result.dictionary?["announce"]?.list {
    // announceList is [BencodeResult]
    for item in announceList {
      print(item.string!)
    }
  }

  if let creationDate = result.dictionary?["creation date"]?.integer {
    print(creationDate)
  }

} catch BencodeDecodeError.invalidFormat {

} catch {

}

Installation

Swift Package Manager

import PackageDescription

let package = Package(
  <...>
  dependencies: [
    .Package(url: "https://github.com/VFK/SwiftyBencode.git", majorVersion: 0, minor: 2)
  ]
  <...>
)