Extends String
, Data
, and URL
adding the ability to easily and efficiently calculate the cryptographic checksum of its associated
contents by adding conformance to the Checksumable
protocol.
Under the hood, Apple's CommonCrypto
framework is used.
- iOS 9 / macOS 10.11 / tvOS 9 / watchOS 2
- Xcode 10.2
- Swift 4.0 / 4.2 / 5.0 / 5.1
MD5
, SHA1
, SHA224
, SHA256
, SHA384
, SHA512
Processing and progress monitoring are performed asynchronously on a background dispatch queue. Progress and completion
closures are, by default, called on the .main
dispatch queue. However, a different DispatchQueue
may be specified.
The function signature for async processing is:
checksum(algorithm:chunkSize:queue:progress:completion:)
In the cases where the payload is fairly small, asynchronous processing may not be required or desirable. For such cases, a synchronous version is provided.
The function signature for sync processing is:
checksum(algorithm:chunkSize:)
Any URLs with schemes file
, http
, or https
may be used as input. However, http
and https
support is currently experimental and has the following requirements:
- The HTTP server must be able to respond to
HEAD
requests in order to determine whether theURL
is reachable. - The HTTP server must be able to serve 206 Partial Content responses.
Support for processing arrays of Checksumable
items is also included and showcased in the examples below.
data.checksum(algorithm: .md5) { result in
switch result {
case .success(let checksum):
// Use checksum
case .failure(let error):
// Unable to obtain checksum
}
}
remoteURL.checksum(algorithm: .sha256) { result in
switch result {
case .success(let checksum):
// Use checksum
case .failure(let error):
// Unable to obtain checksum
}
}
[someURL, anotherURL, yetAnotherURL].checksum(algorithm: .md5) { result in
switch result {
case .success(let checksumResults):
// Use results object
for checksumResult in checksumResults {
guard let url = checksumResult.checksumable as? URL else {
fail("Expected checksumable to be of type URL.")
return
}
if let checksum = checksumResult.checksum {
print("Checksum of \(result.checksumable) is \(checksumResult.checksum)")
} else {
print("Unable to obtain checksum for \(checksumResult.checksumable)")
}
}
case .failure(let error):
// Unable to obtain checksums
}
}
if let checksum = string.checksum(algorithm: .md5) {
// Use checksum
}
if let checksum = data.checksum(algorithm: .md5) {
// Use checksum
}
if let checksum = localURL.checksum(algorithm: .md5) {
// Use checksum
}
You may monitor progress by passing a ProgressHandler
closure to the progress
argument in
checksum(algorithm:chunkSize:queue:progress:completion:)
.
remoteURL.checksum(algorithm: .sha256, progress: { progress in
// Add your progress handling code here.
print("Fraction completed: \(progress.fractionCompleted)")
}) { result in
/// Result handling ommited.
}
Checksum
was written by Ruben Nine (@sonicbee9) and is licensed under the
MIT license. See LICENSE.md.