-
Notifications
You must be signed in to change notification settings - Fork 1
/
Utils.m
493 lines (437 loc) · 17.8 KB
/
Utils.m
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
//
// Utils.m
// iOS_App_Template
//
// Created by mxm on 2021/7/12.
// Copyright © 2021 mxm. All rights reserved.
//
#import "Utils.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCrypto.h>
#import <UIKit/UIImage.h>
#import <sys/mount.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
@implementation Utils
+ (NSString *)md5OfFileAtPath:(NSString *)filePath
{
NSInputStream *is = [NSInputStream inputStreamWithFileAtPath:filePath];
if (nil == is) {
return nil;
}
[is open];
NSUInteger const maxLen = 16384;//16k
uint8_t buffer[maxLen];
NSInteger size = [is read:buffer maxLength:maxLen];
CC_MD5_CTX md5;
CC_MD5_Init(&md5);
while (size > 0) {
CC_MD5_Update(&md5, buffer, (CC_LONG)size);
size = [is read:buffer maxLength:maxLen];
}
[is close];
unsigned char digest[CC_MD5_DIGEST_LENGTH] = {0};
CC_MD5_Final(digest, &md5);
return [NSString stringWithFormat:
@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
digest[0], digest[1], digest[2], digest[3],
digest[4], digest[5], digest[6], digest[7],
digest[8], digest[9], digest[10], digest[11],
digest[12], digest[13], digest[14], digest[15]];
}
//微信用到的
+ (UIImage *)IOCompressImage:(NSData *)data size:(CGSize)size
{
CFDataRef cfdata = CFBridgingRetain(data);
CFStringRef optionKeys[1];
CFTypeRef optionValues[4];
optionKeys[0] = kCGImageSourceShouldCache;
optionValues[0] = (CFTypeRef)kCFBooleanFalse;
CFDictionaryRef sourceOption = CFDictionaryCreate(kCFAllocatorDefault, (const void **)optionKeys, (const void **)optionValues, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
// CGImageSourceRef imageSource = CGImageSourceCreateWithURL(cfurl, sourceOption);
CGImageSourceRef imageSource = CGImageSourceCreateWithData(cfdata, sourceOption);
CFRelease(sourceOption);
if (!imageSource) {
NSLog(@"imageSource is Null!");
return nil;
}
//获取原图片属性
// CFDictionaryRef property = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil);
// NSDictionary *propertys = CFBridgingRelease(property);
// CGFloat height = [propertys[@"PixelHeight"] integerValue]; //图像k宽高,12000
// CGFloat width = [propertys[@"PixelWidth"] integerValue];
//以较大的边为基准
int imageSize = (int)MAX(size.width, size.height);
CFStringRef keys[5];
CFTypeRef values[5];
//创建缩略图等比缩放大小,会根据长宽值比较大的作为imageSize进行缩放
//kCGImageSourceThumbnailMaxPixelSize为生成缩略图的大小。当设置为800,如果图片本身大于800*600,则生成后图片大小为800*600,如果源图片为700*500,则生成图片为800*500
keys[0] = kCGImageSourceThumbnailMaxPixelSize;
CFNumberRef thumbnailSize = CFNumberCreate(NULL, kCFNumberIntType, &imageSize);
values[0] = (CFTypeRef)thumbnailSize;
keys[1] = kCGImageSourceCreateThumbnailFromImageAlways;
values[1] = (CFTypeRef)kCFBooleanTrue;
keys[2] = kCGImageSourceCreateThumbnailWithTransform;
values[2] = (CFTypeRef)kCFBooleanTrue;
keys[3] = kCGImageSourceCreateThumbnailFromImageIfAbsent;
values[3] = (CFTypeRef)kCFBooleanTrue;
keys[4] = kCGImageSourceShouldCacheImmediately;
values[4] = (CFTypeRef)kCFBooleanTrue;
CFDictionaryRef options = CFDictionaryCreate(kCFAllocatorDefault, (const void **)keys, (const void **)values, 4, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CGImageRef thumbnailImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options);
UIImage *resultImg = [UIImage imageWithCGImage:thumbnailImage];
CFRelease(cfdata);
CFRelease(thumbnailSize);
CFRelease(options);
CFRelease(imageSource);
CFRelease(thumbnailImage);
return resultImg;
}
// 获取文件夹大小
+ (unsigned long long)fetchDirSize:(NSString *)dirPath
{
NSFileManager *fm = NSFileManager.defaultManager;
// 应该比 subpathsAtPath 方法节省内存
NSDirectoryEnumerator *de = [fm enumeratorAtPath:dirPath];
unsigned long long size = 0;
for (NSString *subpath in de) {
// NSLog(@"%@", subpath);
size += [fm attributesOfItemAtPath:[dirPath stringByAppendingPathComponent:subpath] error:NULL].fileSize;
}
// 格式化方式:[NSByteCountFormatter stringFromByteCount:size countStyle:NSByteCountFormatterCountStyleFile]
return size;
}
// 获取可用存储空间大小
+ (uint64_t)availableSpace
{
uint64_t totalSpace;
uint64_t totalFreeSpace;
uint64_t totalUsedSpace;
// 以下两种方式都可获取
NSError *error = nil;
NSDictionary *dictionary = [NSFileManager.defaultManager attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
if (error) {
NSLog(@"availableSpace: %@", error);
return 0;
}
if (dictionary) {
totalFreeSpace = [dictionary[NSFileSystemFreeSize] unsignedLongLongValue];
totalSpace = [dictionary[NSFileSystemSize] unsignedLongLongValue];
totalUsedSpace = totalSpace - totalFreeSpace;
NSLog(@"total: %@, free: %@, used: %@", [NSByteCountFormatter stringFromByteCount:totalSpace countStyle:NSByteCountFormatterCountStyleFile], [NSByteCountFormatter stringFromByteCount:totalFreeSpace countStyle:NSByteCountFormatterCountStyleFile], [NSByteCountFormatter stringFromByteCount:totalUsedSpace countStyle:NSByteCountFormatterCountStyleFile]);
return totalFreeSpace;
}
return 0;
// struct statfs buf;
// if (statfs("/", &buf) >= 0) {
// // f_bavail 普通应用程序可用空间,f_bfree 包括保留块(普通应用程序无法使用)在内的可用空间
// totalFreeSpace = buf.f_bsize * buf.f_bavail;
// totalSpace = buf.f_bsize * buf.f_blocks;
// totalUsedSpace = totalSpace - totalFreeSpace;
// }
// NSLog(@"total: %@, free: %@, used: %@", [NSByteCountFormatter stringFromByteCount:totalSpace countStyle:NSByteCountFormatterCountStyleFile], [NSByteCountFormatter stringFromByteCount:totalFreeSpace countStyle:NSByteCountFormatterCountStyleFile], [NSByteCountFormatter stringFromByteCount:totalUsedSpace countStyle:NSByteCountFormatterCountStyleFile]);
// 以上两种方式的结果一样
}
static size_t trimedBytesLength(Byte *const bytes, size_t const dataLen)
{
size_t i = dataLen - 1;
for (; i >= 0; --i) {
if (0x00 != bytes[i]) {
return i + 1;
}
}
if (16 == dataLen) {
return 1;
}
return dataLen;
}
static const Byte iv[] = {8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 6, 6, 6, 6, 6, 6};
+ (NSData *)encryptUseAES128CBC:(NSData *)data key:(Byte *)key
{// 单片机: https://blog.csdn.net/chengjunchengjun/article/details/109322987
if (!data) return nil;
NSUInteger len = data.length;
//AES/ECB/ZeroPadding 是16个byte为一组加密,最后一组不足16个byte要补0
int diff = kCCKeySizeAES128 - (len % kCCKeySizeAES128);
NSUInteger newLen = len;
if (diff > 0) {
newLen = len + diff;
}
Byte newData[newLen];
memcpy(newData, data.bytes, len);
memset(newData+len, 0, diff);
// for (NSUInteger i = len; i < newLen; i++) {
// newData[i] = 0x00;
// }
NSLog(@"-- newLen: %lu", (unsigned long)newLen);
size_t bufferLen = newLen + kCCBlockSizeAES128;
NSLog(@"-- bufferLen: %zu", bufferLen);
// void *buffer = malloc(buffersize);
Byte buffer[bufferLen];
memset(buffer, 0, bufferLen);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(
kCCEncrypt,
kCCAlgorithmAES128,
kNilOptions,
key,
kCCBlockSizeAES128,
iv,
newData,
newLen,
buffer, //缓存结果
bufferLen, //缓存的最大长度
&numBytesEncrypted //加密过的
);
if (cryptStatus == kCCSuccess) return [NSData dataWithBytes:buffer length:numBytesEncrypted];
return nil;
}
+ (NSData *)decryptUseAES128CBC:(NSData *)data key:(Byte *)key
{
if (!data) return nil;
size_t bufferLen = data.length + kCCBlockSizeAES128;
NSLog(@"-- bufferLen: %zu", bufferLen);
// void *buffer = malloc(buffersize);
Byte buffer[bufferLen];
memset(buffer, 0, bufferLen);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(
kCCDecrypt,
kCCAlgorithmAES128,
kNilOptions,
key,
kCCBlockSizeAES128,
iv,
data.bytes,
data.length,
buffer, //缓存结果
bufferLen, //缓存的最大长度
&numBytesEncrypted //加密过的
);
if (cryptStatus == kCCSuccess) return [NSData dataWithBytes:buffer length:trimedBytesLength(buffer, numBytesEncrypted)];
return nil;
}
+ (NSData *)encryptUseAES128ECB:(NSData *)data key:(Byte *)key
{
if (!data) return nil;
NSUInteger len = data.length;
//AES/ECB/ZeroPadding 是16个byte为一组加密,最后一组不足16个byte要补0
int diff = kCCKeySizeAES128 - (len % kCCKeySizeAES128);
NSUInteger newLen = len;
if (diff > 0) {
newLen = len + diff;
}
Byte newData[newLen];
memcpy(newData, data.bytes, len);
memset(newData+len, 0, diff);
// for (NSUInteger i = len; i < newLen; i++) {
// newData[i] = 0x00;
// }
NSLog(@"-- newLen: %lu", (unsigned long)newLen);
size_t bufferLen = newLen + kCCBlockSizeAES128;
NSLog(@"-- bufferLen: %zu", bufferLen);
// void *buffer = malloc(buffersize);
Byte buffer[bufferLen];
memset(buffer, 0, bufferLen);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(
kCCEncrypt,
kCCAlgorithmAES,
kCCOptionECBMode,
key,
kCCBlockSizeAES128,
NULL,
newData,
newLen,
buffer, //缓存结果
bufferLen, //缓存的最大长度
&numBytesEncrypted //加密过的
);
if (cryptStatus == kCCSuccess) return [NSData dataWithBytes:buffer length:numBytesEncrypted];
return nil;
}
+ (NSData *)decryptUseAES128ECB:(NSData *)data key:(Byte *)key
{
if (!data) return nil;
size_t bufferLen = data.length + kCCBlockSizeAES128;
NSLog(@"-- bufferLen: %zu", bufferLen);
// void *buffer = malloc(buffersize);
Byte buffer[bufferLen];
memset(buffer, 0, bufferLen);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(
kCCDecrypt,
kCCAlgorithmAES,
kCCOptionECBMode,
key,
kCCBlockSizeAES128,
NULL,
data.bytes,
data.length,
buffer, //缓存结果
bufferLen, //缓存的最大长度
&numBytesEncrypted //加密过的
);
if (cryptStatus == kCCSuccess) return [NSData dataWithBytes:buffer length:trimedBytesLength(buffer, numBytesEncrypted)];
return nil;
}
+ (NSData *)encryptUseAES128CBCPKCS7:(NSData *)data key:(Byte *)key
{
if (!data) return nil;
NSUInteger len = data.length;
NSLog(@"-- Len: %lu", (unsigned long)len);
size_t bufferLen = len + kCCBlockSizeAES128;
NSLog(@"-- bufferLen: %zu", bufferLen);
// void *buffer = malloc(buffersize);
Byte buffer[bufferLen];
memset(buffer, 0, bufferLen);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(
kCCEncrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding,
key,
kCCBlockSizeAES128,
iv,
data.bytes,
len,
buffer, //缓存结果
bufferLen, //缓存的最大长度
&numBytesEncrypted //加密过的
);
if (cryptStatus == kCCSuccess) return [NSData dataWithBytes:buffer length:numBytesEncrypted];
return nil;
}
+ (NSData *)decryptUseAES128CBCPKCS7:(NSData *)data key:(Byte *)key
{
if (!data) return nil;
size_t bufferLen = data.length;
NSLog(@"-- bufferLen: %zu", bufferLen);
// void *buffer = malloc(buffersize);
Byte buffer[bufferLen];
memset(buffer, 0, bufferLen);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(
kCCDecrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding,
key,
kCCBlockSizeAES128,
iv,
data.bytes,
data.length,
buffer, //缓存结果
bufferLen, //缓存的最大长度
&numBytesEncrypted //加密过的
);
if (cryptStatus == kCCSuccess) return [NSData dataWithBytes:buffer length:numBytesEncrypted];
return nil;
}
NSString * byte2HexString(Byte buf[], size_t len) {
const char hex [] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
char chs[len * 2];
int index = 0;
Byte b;
for (int i = 0; i < len; ++i) {
b = buf[i];
chs[index] = hex[(b >> 4) & 0x0F];
++index;
chs[index] = hex[b & 0x0F];
++index;
}
return [[NSString alloc] initWithBytes:chs length:len * 2 encoding:NSUTF8StringEncoding];
}
/**
#import <AVFoundation/AVFoundation.h>
获取视频的第一帧
@param url 视频文件的链接,可以是远程的,也可以是本地的
@param filePath 缩略图的存放地址
*/
+ (void)createVideoThumbnail:(NSString *)url saveToPath:(NSString *)filePath
{
if ([NSFileManager.defaultManager fileExistsAtPath:filePath]) {
[NSFileManager.defaultManager removeItemAtPath:filePath error:NULL];
}
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL URLWithString:url] options:nil];
AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
gen.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
gen.appliesPreferredTrackTransform = YES;
// 如果我们要精确时间,那么只需要
// assetGen.requestedTimeToleranceBefore = kCMTimeZero;
// assetGen.requestedTimeToleranceAfter = kCMTimeZero;
CMTime time = CMTimeMakeWithSeconds(0, 600);
if (@available(iOS 16.0, *)) {
[gen generateCGImageAsynchronouslyForTime:time completionHandler:^(CGImageRef _Nullable image, CMTime actualTime, NSError * _Nullable error) {
if (NULL == image) {
return;
}
UIImage *videoImage = [[UIImage alloc] initWithCGImage:image];
NSData *data = UIImageJPEGRepresentation(videoImage, 0.9);
[data writeToFile:filePath atomically:YES];
}];
} else {
NSError *error = nil;
// CMTime actualTime;
CGImageRef image = [gen copyCGImageAtTime:time actualTime:NULL error:&error];
if (NULL == image) {
return;
}
UIImage *videoImage = [[UIImage alloc] initWithCGImage:image];
CGImageRelease(image);
NSData *data = UIImageJPEGRepresentation(videoImage, 0.9);
[data writeToFile:filePath atomically:YES];
}
}
+ (void)disableRemoteCommand
{
MPRemoteCommandCenter *rcc = [MPRemoteCommandCenter sharedCommandCenter];
rcc.pauseCommand.enabled = NO;
rcc.playCommand.enabled = NO;
rcc.stopCommand.enabled = NO;
rcc.togglePlayPauseCommand.enabled = NO;
rcc.enableLanguageOptionCommand.enabled = NO;
rcc.disableLanguageOptionCommand.enabled = NO;
rcc.changePlaybackRateCommand.enabled = NO;
rcc.changeRepeatModeCommand.enabled = NO;
rcc.changeShuffleModeCommand.enabled = NO;
rcc.nextTrackCommand.enabled = NO;
rcc.previousTrackCommand.enabled = NO;
rcc.skipForwardCommand.enabled = NO;
rcc.skipBackwardCommand.enabled = NO;
rcc.seekForwardCommand.enabled = NO;
rcc.seekBackwardCommand.enabled = NO;
rcc.changePlaybackPositionCommand.enabled = NO;
rcc.ratingCommand.enabled = NO;
rcc.likeCommand.enabled = NO;
rcc.dislikeCommand.enabled = NO;
rcc.bookmarkCommand.enabled = NO;
[rcc.pauseCommand addTarget:self action:@selector(remoteCommandDoNothing:)];
[rcc.playCommand addTarget:self action:@selector(remoteCommandDoNothing:)];
[rcc.stopCommand addTarget:self action:@selector(remoteCommandDoNothing:)];
[rcc.togglePlayPauseCommand addTarget:self action:@selector(remoteCommandDoNothing:)];
[rcc.enableLanguageOptionCommand addTarget:self action:@selector(remoteCommandDoNothing:)];
[rcc.disableLanguageOptionCommand addTarget:self action:@selector(remoteCommandDoNothing:)];
[rcc.changePlaybackRateCommand addTarget:self action:@selector(remoteCommandDoNothing:)];
[rcc.changeRepeatModeCommand addTarget:self action:@selector(remoteCommandDoNothing:)];
[rcc.changeShuffleModeCommand addTarget:self action:@selector(remoteCommandDoNothing:)];
[rcc.nextTrackCommand addTarget:self action:@selector(remoteCommandDoNothing:)];
[rcc.previousTrackCommand addTarget:self action:@selector(remoteCommandDoNothing:)];
[rcc.skipForwardCommand addTarget:self action:@selector(remoteCommandDoNothing:)];
[rcc.skipBackwardCommand addTarget:self action:@selector(remoteCommandDoNothing:)];
[rcc.seekForwardCommand addTarget:self action:@selector(remoteCommandDoNothing:)];
[rcc.seekBackwardCommand addTarget:self action:@selector(remoteCommandDoNothing:)];
[rcc.changePlaybackPositionCommand addTarget:self action:@selector(remoteCommandDoNothing:)];
[rcc.ratingCommand addTarget:self action:@selector(remoteCommandDoNothing:)];
[rcc.likeCommand addTarget:self action:@selector(remoteCommandDoNothing:)];
[rcc.dislikeCommand addTarget:self action:@selector(remoteCommandDoNothing:)];
[rcc.bookmarkCommand addTarget:self action:@selector(remoteCommandDoNothing:)];
[MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = nil;
}
+ (MPRemoteCommandHandlerStatus)remoteCommandDoNothing:(MPRemoteCommandEvent *)event
{
// [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = nil;
return MPRemoteCommandHandlerStatusCommandFailed;
}
@end