/
UWFile.swift
94 lines (82 loc) · 3.13 KB
/
UWFile.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
//
// UFWFile.swift
// UnfoldingWord
//
// Created by David Solberg on 6/15/15.
//
import UIKit
@objc final class UFWFile {
let sourceDictionary: NSDictionary
let isValid : Bool
/// Returns the data containing the JSON string that represents all the data needed to create teh
var fileData : NSData {
get {
var error : NSError?
if let
data = NSJSONSerialization.dataWithJSONObject(sourceDictionary, options: nil, error: &error),
zipData = data.gzippedDataWithCompressionLevel(0.95) {
return zipData
}
assertionFailure("Could not create gzipped data from dictionary \(sourceDictionary) \n\n error: \(error)")
return NSData()
}
}
/// Returns the top level object used to populate the database with the enclosed file
var topLevelObject : NSDictionary {
get {
if let dictionary = self.sourceDictionary[Constants.FileFormat.TopLevel] as? NSDictionary {
return dictionary;
}
assertionFailure("Could not create dictionary for key \(Constants.FileFormat.TopLevel) from \(self.sourceDictionary)")
return NSDictionary()
}
}
/// Returns a source item to populate each toc item with content and signature json
func sourceItemForUrl(url: NSString) -> UrlSourceItem? {
if let
sources = self.sourceDictionary[Constants.FileFormat.SourcesArray] as? NSDictionary,
sourceContent = sources.valueForKey(url as String) as? NSString
{
return UrlSourceItem(url: url, content: sourceContent)
}
else {
assertionFailure("Could not create sources for url \(url)")
return nil
}
}
init(sourceDictionary : NSDictionary) {
self.isValid = UFWFile.validateSource(sourceDictionary)
self.sourceDictionary = sourceDictionary
}
init(fileData : NSData) {
var dictionary: NSDictionary?
var error : NSError?
if let unzippedData = fileData.gunzippedData() {
if let data = NSJSONSerialization.JSONObjectWithData(unzippedData, options: NSJSONReadingOptions.AllowFragments, error: &error) as? NSDictionary {
dictionary = data
}
}
switch (dictionary) {
case .None:
self.sourceDictionary = NSDictionary()
self.isValid = false
assertionFailure("Could not create dictionary from gzipped data \(fileData) \n\n error: \(error)")
case .Some:
self.sourceDictionary = dictionary!
self.isValid = true
}
}
class func validateSource(source : NSDictionary?) -> Bool {
if let
source = source,
top_level = source[Constants.FileFormat.TopLevel] as? NSDictionary,
sourceArray = source[Constants.FileFormat.SourcesArray] as? NSDictionary
{
return true
}
else {
assertionFailure("At least one object was missing from the source.")
return false
}
}
}