OSDN Git Service

スクリーンショット関連を整理
[kcd/KCD.git] / KCD / ScreenshotRegister.swift
1 //
2 //  ScreenshotRegister.swift
3 //  KCD
4 //
5 //  Created by Hori,Masaki on 2017/11/05.
6 //  Copyright © 2017年 Hori,Masaki. All rights reserved.
7 //
8
9 import Cocoa
10
11
12 extension Notification.Name {
13     
14     static let didRegisterScreenshot = Notification.Name(rawValue: "ScreenshotRegister.didRegisterScreenshot")
15 }
16
17 class ScreenshotRegister {
18     
19     static let screenshotURLKey = "ScreenshotRegister.screenshotURLKey"
20     
21     let url: URL
22     
23     init(_ url: URL) {
24         
25         self.url = url
26     }
27     
28     func registerScreenshot(_ image: NSBitmapImageRep, name: String) {
29         
30         DispatchQueue(label: "Screenshot queue").async {
31             
32             guard let data = image.representation(using: .jpeg, properties: [:]) else { return }
33             
34             let url = self.url
35                 .appendingPathComponent(name)
36                 .appendingPathExtension("jpg")
37             let pathURL = FileManager.default.uniqueFileURL(url)
38             
39             do {
40                 
41                 try data.write(to: pathURL)
42                 
43             } catch {
44                 
45                 print("Can not write image")
46                 return
47             }
48             
49             self.notify(url: pathURL)
50         }
51     }
52     
53     func notify(url: URL) {
54         
55         DispatchQueue.main.async {
56             NotificationCenter.default
57                 .post(name: .didRegisterScreenshot,
58                       object: self,
59                       userInfo: [ScreenshotRegister.screenshotURLKey: url])
60         }
61     }
62     
63 }