Browse files

Add +SHA1HashContentsOfURL:completionHandler:

Only suitable for use on threads with a working runloop at present
  • Loading branch information...
1 parent 617adc3 commit 0b7dcd578912cd3243cf6e0fb429125a07d3c64e @mikeabdullah mikeabdullah committed Jan 24, 2013
Showing with 61 additions and 0 deletions.
  1. +7 −0 KSSHA1Stream.h
  2. +54 −0 KSSHA1Stream.m
View
7 KSSHA1Stream.h
@@ -44,7 +44,14 @@
@interface KSSHA1Stream (KSURLHashing)
+
+ (NSData *)SHA1DigestOfContentsOfURL:(NSURL *)URL;
+
+// Only suitable for calling from threads with a running runloop at present
+// Completion handler is called on an arbitrary thread/queue
+// digest is nil if failed to load for some reason, and then error should give some more info
++ (void)SHA1HashContentsOfURL:(NSURL *)url completionHandler:(void (^)(NSData *digest, NSError *error))handler __attribute__((nonnull(1,2)));
+
@end
View
54 KSSHA1Stream.m
@@ -28,6 +28,19 @@
#import "KSSHA1Stream.h"
+@interface KSAsyncSHA1Stream : KSSHA1Stream
+{
+ void (^_completionBlock)(NSData *digest, NSError *error);
+}
+
+- (id)initWithURL:(NSURL *)url completionHandler:(void (^)(NSData *digest, NSError *error))handler __attribute__((nonnull(1,2)));
+
+@end
+
+
+#pragma mark -
+
+
@implementation KSSHA1Stream
- (id)init;
@@ -176,6 +189,11 @@ + (NSData *)SHA1DigestOfContentsOfURL:(NSURL *)URL;
return result;
}
++ (void)SHA1HashContentsOfURL:(NSURL *)url completionHandler:(void (^)(NSData *digest, NSError *error))handler __attribute__((nonnull(1,2)));
+{
+ [[[KSAsyncSHA1Stream alloc] initWithURL:url completionHandler:handler] release];
+}
+
- (id)initWithURL:(NSURL *)URL;
{
if (self = [self init])
@@ -202,3 +220,39 @@ - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)err
}
@end
+
+
+#pragma mark -
+
+
+@implementation KSAsyncSHA1Stream
+
+- (id)initWithURL:(NSURL *)url completionHandler:(void (^)(NSData *digest, NSError *error))handler;
+{
+ // Rely on super's NSURLConnection to retain us
+ if (self = [self initWithURL:url])
+ {
+ _completionBlock = [handler copy];
+ }
+ return self;
+}
+
+- (void)dealloc;
+{
+ [_completionBlock release];
+ [super dealloc];
+}
+
+- (void)connectionDidFinishLoading:(NSURLConnection *)connection
+{
+ [super connectionDidFinishLoading:connection];
+ _completionBlock([self SHA1Digest], nil);
+}
+
+- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
+{
+ [super connection:connection didFailWithError:error];
+ _completionBlock(nil, error);
+}
+
+@end

0 comments on commit 0b7dcd5

Please sign in to comment.