2017-02-22 111 views
0

我要计算所选文件(图片,视频)计算视频文件的MD5(哈希)

在我的代码图像计算

工作不工作很好,但视频计算校验和。

我使用CryptoSwift

这里是我的代码,我做什么

import CryptoSwift 

class MD5Calculator { 

    static func imageChecksum(imageArray: [UIImage], onCalculated: @escaping ([String]) -> Void){ 

     DispatchQueue.global(qos: .userInitiated).async { 

      var array: [String] = []       
      for chosenImage in imageArray { 
       if let jpegData = UIImageJPEGRepresentation(chosenImage, 80) { 
        let checksum = jpegData.md5() 
        let chsum = checksum.toHexString() 
        array.append(chsum) 
       } 
      } 

      DispatchQueue.main.async { 
       onCalculated(array) 
      } 
     } 
    } 

    static func videoChecksum(videoURLs:[NSURL], onCalculated: @escaping ([String]) -> Void) { 
     DispatchQueue.global(qos: .userInitiated).async { 

      var array: [String] = [] 

      for url in videoURLs { 
       if let videoData = Data(contentsOf: url as URL, options: Data.ReadingOptions) { 
        let checksum = videoData.md5() 
        let chsum = checksum.toHexString() 
        array.append(chsum) 

       } 
      } 

      DispatchQueue.main.async { 
       onCalculated(array) 
      } 
     } 
    } 
} 

在videoChecksum我不能让我的数据有语法错误行

if let videoData = Data(contentsOf: url as URL, options: Data.ReadingOptions) 

错误是:

Cannot convert value of type 'Data.ReadingOptions.Type' (aka 'NSData.ReadingOptions.Type') to expected argument type 'Data.ReadingOptions' (aka 'NSData.ReadingOptions') 

这是数据类的构造函数

public init(contentsOf url: URL, options: Data.ReadingOptions = default) throws 

我的问题是

1.我怎么能拿视频文件

2的数据如果有另一种方式来获得数据和计算校验和请建议我

3.如果你知道什么语法错误,请告诉我如何解决它。

回答

2

它调用

let videoData = Data(contentsOf: url as URL, options: Data.ReadingOptions) 

时,因为options参数期待ReadingOptions价值之一,并要传递的类型本身好像你有一个语法错误。一个有效的调用看起来是这样的:

let videoData = Data(contentsOf: url as URL, options: Data.ReadingOptions.uncached) 

(可能的值,见official documentation

如果你不确定要提供什么样的价值,你可以省略传递参数,因为它是默认的,即:

let videoData = Data(contentsOf: url as URL) 

编辑:
还要注意的是Data(contentsOf:options:)初始化器“throws”所以最好你应该换行中的呼叫DO/try/catch语句是这样的:

for url in videoURLs { 
    do { 
     let videoData = try Data(contentsOf: url as URL) 
     let checksum = videoData.md5() 
     let chsum = checksum.toHexString() 
     array.append(chsum) 
    } catch { 
     // TODO: Handle error 
     print(error.localizedDescription) 
    } 
} 

希望这有助于。

+0

非常感谢。你救了我的命。 – fish40

+0

很高兴能够听到:)另请参阅我的关于异常处理的编辑。 – Olivier

0

尝试此

ALAssetRepresentation *代表= [资产defaultRepresentation]; Byte buffer =(Byte)malloc((NSUInteger)rep.size); NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:(NSUInteger)rep。大小错误:无]; NSData * data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];