summaryrefslogtreecommitdiff
path: root/Sora/Data/Moebooru/MoebooruPostXMLParser.swift
blob: 418a9c6dc3f89274d26d02607c9f8f0818709857 (plain) (blame)
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
import Foundation

class MoebooruPostXMLParser: NSObject, XMLParserDelegate {
    private var posts: [MoebooruPost] = []

    func parse(data: Data) -> [MoebooruPost] {
        let parser = XMLParser(data: data)

        parser.delegate = self
        parser.parse()

        return posts
    }

    func parser(_: XMLParser, didStartElement elementName: String,
                namespaceURI _: String?, qualifiedName _: String?,
                attributes attributeDict: [String: String])
    {
        if elementName == "post",
           let id = Int(attributeDict["id"] ?? ""),
           let createdAtTimestamp = TimeInterval(attributeDict["created_at"] ?? ""),
           let score = Int(attributeDict["score"] ?? ""),
           let width = Int(attributeDict["width"] ?? ""),
           let height = Int(attributeDict["height"] ?? "")
        {
            posts.append(MoebooruPost(
                id: id,
                tags: attributeDict["tags"]?.components(separatedBy: " ") ?? [],
                createdAt: Date(timeIntervalSince1970: createdAtTimestamp),
                author: attributeDict["author"] ?? "",
                source: URL(string: attributeDict["source"] ?? ""),
                score: score,
                fileURL: URL(string: attributeDict["file_url"] ?? ""),
                previewURL: URL(string: attributeDict["preview_url"] ?? ""),
                sampleURL: URL(string: attributeDict["sample_url"] ?? ""),
                jpegURL: URL(string: attributeDict["jpeg_url"] ?? ""),
                width: width,
                height: height
            ))
        }
    }
}