iOS开发(OC)

iOS获取相册视频的MD5方法(最好)

2017-05-12  本文已影响843人  爱恨的潮汐

在网上查了好多方法复制过来都有问题,最后找了这个是最准确的,帮大家减少走弯路。

ADUtilHelper.h

//获取视频MD5
#import <Foundation/Foundation.h>
#import <SystemConfiguration/CaptiveNetwork.h>
@interface ADUtilHelper : NSObject

+(NSString *)getFileMD5WithPath:(NSString*)path;
+(NSString *)getWifiName;
@end

ADUtilHelper.m

#define FileHashDefaultChunkSizeForReadingData 1024*8 

#import "ADUtilHelper.h"
#include <CommonCrypto/CommonDigest.h>

@implementation ADUtilHelper

+(NSString*)getFileMD5WithPath:(NSString*)path
{
    return (__bridge_transfer NSString *)FileMD5HashCreateWithPath((__bridge CFStringRef)path, FileHashDefaultChunkSizeForReadingData);
}

CFStringRef FileMD5HashCreateWithPath(CFStringRef filePath,size_t chunkSizeForReadingData) {
    // Declare needed variables
    CFStringRef result = NULL;
    CFReadStreamRef readStream = NULL;
    // Get the file URL
    CFURLRef fileURL =
    CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
                                  (CFStringRef)filePath,
                                  kCFURLPOSIXPathStyle,
                                  (Boolean)false);
    if (!fileURL) goto done;
    // Create and open the read stream
    readStream = CFReadStreamCreateWithFile(kCFAllocatorDefault,
                                            (CFURLRef)fileURL);
    if (!readStream) goto done;
    bool didSucceed = (bool)CFReadStreamOpen(readStream);
    if (!didSucceed) goto done;
    // Initialize the hash object
    CC_MD5_CTX hashObject;
    CC_MD5_Init(&hashObject);
    // Make sure chunkSizeForReadingData is valid
    if (!chunkSizeForReadingData) {
        chunkSizeForReadingData = FileHashDefaultChunkSizeForReadingData;
    }
    // Feed the data to the hash object
    bool hasMoreData = true;
    while (hasMoreData) {
        uint8_t buffer[chunkSizeForReadingData];
        CFIndex readBytesCount = CFReadStreamRead(readStream,(UInt8 *)buffer,(CFIndex)sizeof(buffer));
        if (readBytesCount == -1) break;
        if (readBytesCount == 0) {
            hasMoreData = false;
            continue;
        }
        CC_MD5_Update(&hashObject,(const void *)buffer,(CC_LONG)readBytesCount);
    }
    // Check if the read operation succeeded
    didSucceed = !hasMoreData;
    // Compute the hash digest
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5_Final(digest, &hashObject);
    // Abort if the read operation failed
    if (!didSucceed) goto done;
    // Compute the string result
    char hash[2 * sizeof(digest) + 1];
    for (size_t i = 0; i < sizeof(digest); ++i) {
        snprintf(hash + (2 * i), 3, "%02x", (int)(digest[i]));
    }
    result = CFStringCreateWithCString(kCFAllocatorDefault,(const char *)hash,kCFStringEncodingUTF8);
    
done:
    if (readStream) {
        CFReadStreamClose(readStream);
        CFRelease(readStream);
    }
    if (fileURL) {
        CFRelease(fileURL);
    }
    return result;
}

+(NSString *)getWifiName{
    NSString *wifiName = @"";
    
    CFArrayRef wifiInterfaces = CNCopySupportedInterfaces();
    
    if (!wifiInterfaces) {
        return nil;
    }
    
    NSArray *interfaces = (__bridge NSArray *)wifiInterfaces;
    
    for (NSString *interfaceName in interfaces) {
        CFDictionaryRef dictRef = CNCopyCurrentNetworkInfo((__bridge CFStringRef)(interfaceName));
        
        if (dictRef) {
            NSDictionary *networkInfo = (__bridge NSDictionary *)dictRef;
            NSLog(@"network info -> %@", networkInfo);
            wifiName = [networkInfo objectForKey:(__bridge NSString *)kCNNetworkInfoKeySSID];
            NSLog(@"wifiName----%@",wifiName);
            CFRelease(dictRef);
        }
    }
    
    CFRelease(wifiInterfaces);
    return wifiName;


}
@end

补充:相册视频获取url并把视频文件存入沙盒

获取相册视频

//代理
UIImagePickerControllerDelegate,UINavigationControllerDelegate
  //从手机相册选取视频
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.delegate = self;
            //视频编辑
            imagePicker.allowsEditing = YES;
            //相册选取==UIImagePickerControllerSourceTypeSavedPhotosAlbum(打开所有视频,而不是列表)
            imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            //设置选取类型,只能是视频
            imagePicker.mediaTypes =  [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil];
            
            [self presentViewController:imagePicker animated:YES completion:nil];

#pragma mark -
#pragma UIImagePickerController Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(NSString*)kUTTypeImage]) {
        //获取到图片
//        UIImage  *img = [info objectForKey:UIImagePickerControllerEditedImage];
//        self.fileData = UIImageJPEGRepresentation(img, 1.0);
    } else if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(NSString*)kUTTypeMovie]) {
        //获取到视频路径(有些视频没有这个值,所以不用他)
//        NSString *videoPath1 = [[info objectForKey:UIImagePickerControllerMediaURL] path];

        //获取视频的url(所有视频都有这个值)
        NSURL * videoXT_URL = [info objectForKey:UIImagePickerControllerReferenceURL];
         [picker dismissViewControllerAnimated:YES completion:nil];
    }
}


存入沙盒

//系统视频上传存储沙盒路径(再用)临时缓存:NSCachesDirectory
#define KVideoUrlPath   \
[[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"XiumeiVideoURLDWB"]
// 将原始视频的URL转化为NSData数据,写入沙盒
- (void)getPhoneDateVideo:(NSURL *)url
{
    // 解析一下,为什么视频不像图片一样一次性开辟本身大小的内存写入?
    // 想想,如果1个视频有1G多,难道直接开辟1G多的空间大小来写?
    // 创建存放原始图的文件夹--->VideoURL
    NSFileManager * fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:KVideoUrlPath]) {
        [fileManager createDirectoryAtPath:KVideoUrlPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (url) {
            [assetLibrary assetForURL:url resultBlock:^(ALAsset *asset) {
                ALAssetRepresentation *rep = [asset defaultRepresentation];
                //路径后面拼接当前日期做区分,否则会读取成一个文件
//                NSString * dateString = [NSString getNowDateFormat:@"yyyyMMddHHmmss"];
                //视频名字
                NSString * dateString = rep.filename;
//                NSLog(@"%@",dateString);
                NSString * videoPath = [KVideoUrlPath stringByAppendingPathComponent:dateString];
                const char *cvideoPath = [videoPath UTF8String];
                FILE *file = fopen(cvideoPath, "a+");
                if (file) {
                    const int bufferSize = 11024 * 1024;
                    // 初始化一个1M的buffer
                    Byte *buffer = (Byte*)malloc(bufferSize);
                    NSUInteger read = 0, offset = 0, written = 0;
                    NSError* err = nil;
                    if (rep.size != 0)
                    {
                        do {
                            read = [rep getBytes:buffer fromOffset:offset length:bufferSize error:&err];
                            written = fwrite(buffer, sizeof(char), read, file);
                            offset += read;
                        } while (read != 0 && !err);//没到结尾,没出错,ok继续
                    }
                    // 释放缓冲区,关闭文件
                    free(buffer);
                    buffer = NULL;
                    fclose(file);
                    file = NULL;
                    
                    // UI的更新记得放在主线程,要不然等子线程排队过来都不知道什么年代了,会很慢的
                    dispatch_async(dispatch_get_main_queue(), ^{
                        //获取视频MD5
                       self.videoStringMD5 = [ADUtilHelper getFileMD5WithPath:videoPath];
//                        NSLog(@"视频的MD5:%@",self.videoStringMD5);
                    });
                }else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        [DWBToast showCenterWithText:@"视频处理失败"];
                        
                    });
                }
            } failureBlock:^(NSError *error) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [DWBToast showCenterWithText:@"视频处理失败"];
                    
                });
                
            }];
        }
    });
}

上一篇下一篇

猜你喜欢

热点阅读