OSDN Git Service

Squashed commit of the following: Swiftに変換した
[kcd/KCD.git] / KCD / JSONReciever.swift
1 //
2 //  JSONReciever.swift
3 //  KCD
4 //
5 //  Created by Hori,Masaki on 2017/02/02.
6 //  Copyright © 2017年 Hori,Masaki. All rights reserved.
7 //
8
9 import Cocoa
10
11 class JSONReciever {
12     init(queue: Queue) {
13         self.queue = queue
14         CustomHTTPProtocol.classDelegate = self
15     }
16     
17     fileprivate let queue: Queue
18     fileprivate var recievers: [URLProtocol: NSMutableData] = [:]
19 }
20
21 extension JSONReciever: CustomHTTPProtocolDelegate {
22     private func acceptProtocol(_ proto: URLProtocol) {
23         recievers[proto] = NSMutableData()
24         Debug.print("Accept protorol ->", proto, level: .full)
25     }
26     private func data(_ forProtocol: URLProtocol) -> NSMutableData? {
27         return recievers[forProtocol]
28     }
29     private func clearProtocol(_ proto: URLProtocol) {
30         recievers[proto] = nil
31     }
32     
33     func customHTTPProtocol(_ proto: CustomHTTPProtocol, didRecieve response: URLResponse) {
34         if let pathComp = proto.request.url?.pathComponents,
35             pathComp.contains("kcsapi") {
36             acceptProtocol(proto)
37         }
38     }
39     func customHTTPProtocol(_ proto: CustomHTTPProtocol, didRecieve data: Data) {
40         self.data(proto)?.append(data)
41     }
42     func customHTTPProtocolDidFinishLoading(_ proto: CustomHTTPProtocol) {
43         defer { clearProtocol(proto) }
44         guard let data = self.data(proto),
45             let response = APIResponse(request: proto.request, data: data as Data)
46             else { return }
47         queue.enqueue(response)
48     }
49     func customHTTPProtocol(_ proto: CustomHTTPProtocol, didFailWithError error: Error) {
50         Debug.print("Connection Error! \nRequest: \(proto.request)\nError:\(error)", level: .full)
51         clearProtocol(proto)
52     }
53 }