CNLivePhotoManager.swift
2.66 KB
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
//
// CNLivePhotoManager.swift
// metaCode
//
// Created by zx on 2024/9/13.
//
import UIKit
import Photos
class CNLivePhotoManager: NSObject {
// MARK: - 权限请求
func requestPhotoLibraryPermission(completion: ((PHAuthorizationStatus) -> Void)? = nil) {
PHPhotoLibrary.requestAuthorization { status in
DispatchQueue.main.async {
completion?(status)
switch status {
case .authorized:
print("Access granted by user")
case .denied, .restricted:
print("User denied access")
case .notDetermined:
// 这种情况理论上不会发生,因为已经调用了requestAuthorization
break
case .limited:
break
@unknown default:
fatalError()
}
}
}
}
// MARK: - 下载图片
func downloadImage(from url: URL, completion: @escaping (UIImage?, Error?) -> Void) {
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else {
completion(nil, error)
return
}
DispatchQueue.main.async {
let image = UIImage(data: data)
completion(image, nil)
}
}.resume()
}
// MARK: - 保存图片到相册
@objc func saveImage(_ image: UIImage, completion: @escaping (Bool) -> Void){
// UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
UIImageWriteToSavedPhotosAlbum(image, self, #selector(imageSaved(_:error:context:)), nil)
}
@objc func imageSaved(_ image: UIImage, error: Error?, context: UnsafeMutableRawPointer?){
if error != nil{
//false
showMessage(message: "保存失败")
return
}
//true
showMessage(message: "保存成功")
}
// MARK: - 示例用法
func saveImageFromURL(url: URL) {
self.requestPhotoLibraryPermission { status in
guard status == .authorized else {
return
}
self.downloadImage(from: url) { image, error in
guard let image = image, error == nil else {
print("Failed to download image: \(error?.localizedDescription ?? "Unknown error")")
return
}
self.saveImage(image) { isSucc in
if isSucc{
}
}
}
}
}
}