iOS獲取相簿視訊的MD5方法(最好)

weixin_34236497發表於2017-05-12

在網上查了好多方法複製過來都有問題,最後找了這個是最準確的,幫大家減少走彎路。

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:@"視訊處理失敗"];
                    
                });
                
            }];
        }
    });
}

相關文章