OSDN Git Service

洋上補給の補強増設用のショートネームをつけた
[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 final class JSONReciever {
12     
13     private let queue: Queue<APIResponse>
14     private var recievers: [URLProtocol: NSMutableData] = [:]
15     
16     init(queue: Queue<APIResponse>) {
17         
18         self.queue = queue
19         CustomHTTPProtocol.classDelegate = self
20     }
21 }
22
23 extension JSONReciever: CustomHTTPProtocolDelegate {
24     
25     private func storeData(for proto: URLProtocol) {
26         
27         recievers[proto] = NSMutableData()
28         
29         Debug.print("Accept protorol ->", proto, level: .full)
30     }
31     
32     private func data(for proto: URLProtocol) -> NSMutableData? {
33         
34         return recievers[proto]
35     }
36     
37     private func releaseeData(for proto: URLProtocol) {
38         
39         recievers[proto] = nil
40     }
41     
42     func customHTTPProtocol(_ proto: CustomHTTPProtocol, didRecieve response: URLResponse) {
43         
44         if let pathComp = proto.request.url?.pathComponents,
45             pathComp.contains("kcsapi") {
46             
47             storeData(for: proto)
48         }
49     }
50     
51     func customHTTPProtocol(_ proto: CustomHTTPProtocol, didRecieve data: Data) {
52         
53         self.data(for: proto)?.append(data)
54     }
55     
56     func customHTTPProtocolDidFinishLoading(_ proto: CustomHTTPProtocol) {
57         
58         defer { releaseeData(for: proto) }
59         
60         guard let data = self.data(for: proto),
61             let response = APIResponse(request: proto.request, data: data as Data) else {
62                 
63                 return
64         }
65         
66         queue.enqueue(response)
67     }
68     
69     func customHTTPProtocol(_ proto: CustomHTTPProtocol, didFailWithError error: Error) {
70         
71         Debug.print("Connection Error! \nRequest: \(proto.request)\nError:\(error)", level: .full)
72         
73         releaseeData(for: proto)
74     }
75 }