CNLiveCommonQiniuTool.swift
3.43 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
90
91
92
93
94
95
96
97
98
99
100
//
// CNLiveCommonQiniuTool.swift
// metaCode
//
// Created by open on 2023/6/15.
//
import Foundation
import Qiniu
import YYCategories
import CNLiveRequestBastKit
typealias ProgressBlcok = (String,CGFloat)
typealias SuccessBlock = (String,String)
class UploadManager: NSObject {
var successBlock: SuccessBlock?
var progressBlcok: ProgressBlcok?
private var _qnUploadManager = QNUploadManager()
static let shared = UploadManager()
private override init() {
super.init()
let config = QNConfiguration.build { builder in
builder?.useHttps = true;
do {
builder?.recorder = try QNFileRecorder(folder: "元码")
} catch {}
}
_qnUploadManager = QNUploadManager(configuration: config)
}
static func uploadImage(imageData: NSData, progressBlock: ProgressBlcok, successBlock: SuccessBlock) {
let key = UploadManager.createImageFileName()
UploadManager.shared.successBlock = successBlock
UploadManager.shared.progressBlcok = progressBlock
UploadManager.uploadData(data: imageData, key: key)
}
/// 上传图片
/// - Parameters:
/// - data: 上传数据
/// - key: key
/// - uploadProgress: 上传进度
/// - resultBlock: 结果
static private func uploadData(data: NSData, key: String) {
CNLiveNetworking.setAllowRequestDefaultArgument(true)
CNLiveNetworking.setupShowDataResult(false)
CNLiveNetworking.requestNetwork(with: .POST, urlString: "\(CNLiveEnvironmentManager.shared.baseUrl_shop)/Api/Index3/getQiniuToken", param: [:], cacheType: .networkOnly) { task, result, error in
if (error == nil) {
let resp = result as! NSDictionary
let errorCode = "\(resp["code"] ?? 0)"
if (errorCode == "0") {
let data = resp["data"] as! Dictionary<String, Any>
let token = data["token"] as! String
if token.isNotBlank() {
var uploadModel = QiNiuUploadModel.init()
uploadModel.isCancel = false
uploadModel.key = key
let uploadOption = QNUploadOption.init(mime: nil, progressHandler: { key, percent in
DispatchQueue.main.async {
// UploadManager.shared.progressBlock
}
}, params: nil, checkCrc: false) {
return uploadModel.isCancel
}
}
} else {
showMessage(message: resp["message"] as! String)
}
} else {
showMessage(message: error!.localizedDescription)
}
}
}
/// 设置图片名称
/// - Returns: 图片名
static private func createImageFileName() -> String {
let date = NSDate()
let currentTimeInterval = NSDate(timeIntervalSince1970: 0)
let imageName = "802/mateCode/img/\(date.string(withFormat: "yyyyMMdd") ?? "0000")/\(arc4random()%10).jpg"
return imageName
}
}
class QiNiuUploadModel: BaseModel {
required init() {
self.uploadOption = QNUploadOption.defaultOptions()
}
///上传文件的key
var key:String = ""
var uploadOption:QNUploadOption
var isCancel:Bool = false
}