Browse files

Initial commit

  • Loading branch information...
0 parents commit 54f7ee42e5630a2daf7f03c0bf393fb7334657ee @mysteriouspants committed Dec 28, 2011
Showing with 317 additions and 0 deletions.
  1. +29 −0 FSURLOperation.h
  2. +206 −0 FSURLOperation.m
  3. +26 −0 LICENSE.md
  4. +56 −0 README.md
29 FSURLOperation.h
@@ -0,0 +1,29 @@
+//
+// FSURLOperation.h
+//
+// Created by Christopher Miller on 10/31/11.
+// Copyright (c) 2011 Christopher Miller. All rights reserved.
+//
+// Pilfers liberally from Gowalla's AFNetworking. I hope they don't mind.
+
+#import <Foundation/Foundation.h>
+
+@interface FSURLOperation : NSOperation
+
+@property (strong) NSURLRequest* request; // changing this after the request has started produces undefined behavior.
+@property (strong) NSHTTPURLResponse* response;
+@property (strong) NSMutableData* payload;
+@property (strong) NSError * error;
+@property (strong) NSThread* targetThread; // changing this after the request has started produces undefined behavior.
+@property (copy) void(^onFinish)(NSHTTPURLResponse* resp, NSData* payload, NSError* error);
+
++ (FSURLOperation*)URLOperationWithRequest:(NSURLRequest*)req
+ completionBlock:(void(^)(NSHTTPURLResponse* resp, NSData* payload, NSError* error))completion;
++ (FSURLOperation*)URLOperationWithRequest:(NSURLRequest*)req
+ completionBlock:(void(^)(NSHTTPURLResponse* resp, NSData* payload, NSError* error))completion
+ onThread:(NSThread*)thread;
+
+- (id)initWithRequest:(NSURLRequest*)_request;
+- (void)startOnThread:(NSThread*)thread; // completely ignore targetThread and just run this on whatever the heck thread I say, dangit!
+
+@end
206 FSURLOperation.m
@@ -0,0 +1,206 @@
+//
+// FSURLOperation.m
+//
+// Created by Christopher Miller on 10/31/11.
+// Copyright (c) 2011 Christopher Miller. All rights reserved.
+//
+
+#import "FSURLOperation.h"
+
+enum FSURLOperationState {
+ ready,
+ executing,
+ cancelled,
+ finished
+ } FSURLOperationState;
+
+@interface FSURLOperation ()
+
+@property (readwrite, assign) enum FSURLOperationState state;
+@property (readwrite, retain) NSURLConnection* connection;
+@property (readwrite, retain) NSSet* runLoopModes;
+@property (readwrite, retain) NSMutableData* dataAccumulator;
+
++ (NSThread*)networkRequestThread;
+- (void)finish;
+
+@end
+
+@implementation FSURLOperation
+
+@synthesize request;
+@synthesize response;
+@synthesize payload;
+@synthesize error;
+
+@synthesize state;
+@synthesize connection;
+@synthesize runLoopModes;
+@synthesize dataAccumulator;
+@synthesize targetThread;
+@synthesize onFinish;
+
++ (FSURLOperation*)URLOperationWithRequest:(NSURLRequest*)req
+ completionBlock:(void(^)(NSHTTPURLResponse* resp, NSData* payload, NSError* error))completion
+{
+ FSURLOperation* operation = [[self alloc] initWithRequest:req];
+ operation.onFinish = completion;
+ operation.targetThread = [self networkRequestThread];
+ return operation;
+}
+
++ (FSURLOperation*)URLOperationWithRequest:(NSURLRequest*)req
+ completionBlock:(void(^)(NSHTTPURLResponse* resp, NSData* payload, NSError* error))completion
+ onThread:(NSThread*)thread
+{
+ FSURLOperation* operation = [[self alloc] initWithRequest:req];
+ operation.onFinish = completion;
+ if (thread)
+ operation.targetThread = thread;
+ else
+ operation.targetThread = [self networkRequestThread];
+
+ return operation;
+}
+
++ (void)networkRequestThreadEntryPoint:(id)__unused object
+{
+ do {
+ @autoreleasepool {
+ [[NSRunLoop currentRunLoop] run];
+ }
+ } while (YES) ;
+}
+
++ (NSThread*)networkRequestThread
+{
+ static NSThread* networkReqThread = nil;
+
+ static dispatch_once_t onceToken;
+ dispatch_once(&onceToken, ^{
+ networkReqThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil];
+ [networkReqThread setName:@"net.fsdev.FSURLOperation-Work-Thread"];
+ [networkReqThread start];
+ });
+
+ return networkReqThread;
+}
+
+- (id)initWithRequest:(NSURLRequest *)_request
+{
+ self = [super init];
+ if (self) {
+ request = _request;
+ self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes];
+ }
+ return self;
+}
+
+- (void)finish
+{
+ [self willChangeValueForKey:@"isFinished"];
+ self.state = finished;
+ self.onFinish(self.response, self.payload, self.error);
+ [self didChangeValueForKey:@"isFinished"];
+}
+
+- (void)operationDidStart
+{
+ if ([self isCancelled]) {
+ [self finish];
+ return;
+ }
+
+ self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO];
+
+ NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
+ for (NSString* runLoopMode in self.runLoopModes) {
+ [self.connection scheduleInRunLoop:runLoop forMode:runLoopMode];
+ }
+
+ [self.connection start];
+}
+
+- (void)startOnThread:(NSThread*)thread
+{
+ if (![self isReady])
+ return;
+
+ self.state = executing;
+
+ [self performSelector:@selector(operationDidStart) onThread:thread withObject:nil waitUntilDone:YES modes:[self.runLoopModes allObjects]];
+}
+
+#pragma mark NSOperation
+
+- (void)start
+{
+ if (![self isReady])
+ return;
+
+ self.state = executing;
+
+ [self performSelector:@selector(operationDidStart) onThread:self.targetThread withObject:nil waitUntilDone:YES modes:[self.runLoopModes allObjects]];
+}
+
+- (BOOL)isConcurrent
+{
+ return YES;
+}
+
+- (BOOL)isExecuting
+{
+ return self.state == executing;
+}
+
+- (BOOL)isFinished
+{
+ return self.state == finished;
+}
+
+#pragma mark NSURLConnectionDelegate
+
+- (void) connection:(NSURLConnection*)connection
+ didSendBodyData:(NSInteger)bytesWritten
+ totalBytesWritten:(NSInteger)totalBytesWritten
+totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
+{
+
+}
+
+- (void)connection:(NSURLConnection*)__unused conn
+didReceiveResponse:(NSURLResponse *)resp
+{
+ self.response = (NSHTTPURLResponse*)resp;
+
+ NSUInteger maxCapacity = MAX((NSUInteger)llabs(response.expectedContentLength), 1024);
+ NSUInteger capacity = MIN(maxCapacity, 1024 * 1024 * 8);
+
+ self.dataAccumulator = [NSMutableData dataWithCapacity:capacity];
+}
+
+- (void)connection:(NSURLConnection*)__unused conn
+ didReceiveData:(NSData*)data
+{
+ [self.dataAccumulator appendData:data];
+}
+
+- (void)connectionDidFinishLoading:(NSURLConnection*)__unused conn
+{
+ self.payload = [NSData dataWithData:self.dataAccumulator];
+ dataAccumulator = nil;
+
+ [self finish];
+}
+
+- (void)connection:(NSURLConnection*)__unused conn
+ didFailWithError:(NSError *)err
+{
+ self.error = err;
+
+ self.dataAccumulator = nil;
+
+ [self finish];
+}
+
+@end
26 LICENSE.md
@@ -0,0 +1,26 @@
+# Firestorm Development Open-Source License
+_Version 0.1_
+
+This software is licensed under the Firestorm Development Open-Source License, which is a dual-licensing under the BSD and MIT license. Pursuant to these terms, you may use this software under the terms of either the BSD or MIT licenses - not both. One or the other, no mix-and-match. The license text of both licenses follows for clarity:
+
+## 2-clause BSD license:
+> Copyright 2011 Christopher Miller. All rights reserved.
+>
+> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+>
+> 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+>
+> 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+>
+> THIS SOFTWARE IS PROVIDED BY Christopher Miller "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Christopher Miller OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+>
+> The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Christopher Miller.
+
+## MIT license:
+> Copyright (c) 2011 Christopher Miller
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
56 README.md
@@ -0,0 +1,56 @@
+# FSURLOperation
+
+Easily enqueue `NSURLRequest`s into an `NSOperationQueue`, set up dependencies, run on threads, and just overall bang out web traffic like a boss.
+
+What does this get you that other tools don't? Not a whole lot! So why should you care?
+
+- It's minimalist, and therefore very flexible.
+- It's designed for the flexibility to function correctly in a heavily multi-threaded environment.
+
+## FSURLOperation might be for you if you're thinking these thoughts:
+
+- I have to make a lot of URL requests
+- Other wrappers are too heavy and/or fail
+- I like blocks
+- I think blocks like me
+- I hate not having direct and easy access to the `NSURLResponse` of a request
+- I hate not having direct and easy access to the `NSData` of a request
+- I want to have children with `NSOperationQueue`, but I don't know the right phone number to call and set up a date
+
+## You've piqued my interest; show me an example!
+
+Fine:
+
+```
+NSURLRequest* req =
+ [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://fsdev.net/"]];
+NSData* mySite = nil;
+FSURLOperation* oper =
+ [FSURLOperation URLOperationWithRequest:req
+ completionBlock:^(NSHTTPURLResponse* resp,
+ NSData* payload,
+ NSError* asplosion) {
+ mySite = payload;
+ }];
+NSBlockOperation* onFinish =
+ [NSBlockOperation blockOperationWithBlock:^{
+ NSMutableURLRequest* spamReq =
+ [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.spam.com/"]];
+ [spamReq setHTTPBody:mySite];
+ FSURLOperation* spamOper =
+ [FSURLOperation URLOperationWithRequest:req
+ completionBlock:^(NSHTTPURLResponse* resp,
+ NSData* payload,
+ NSError* aspolsion) {
+ NSLog(@"%@", [payload fs_stringValue]);
+ }];
+ [[NSOperationQueue mainQueue] addOperation:spamOper];
+ }];
+[onFinish addDependency:oper];
+[[NSOperationQueue mainQueue] addOperations:[NSArray arrayWithObjects:onFinish, oper, nil]
+ waitUntilDone:NO];
+```
+
+In layman's terms, "do this web request, then after that perform this code." I think it's pretty damn awesome, and so I'm sharing it with you. It's saved me a bucket load of not-lulz when dealing with web requests that begat web requests which begat web requests which begat a threadlock. I'll wager that it can save you some time, too.
+
+Enjoy!

0 comments on commit 54f7ee4

Please sign in to comment.