Ben Copsey

First public release

//
// ASIHTTPRequest.h
//
// Created by Ben Copsey on 04/10/2007.
// Copyright 2007-2008 All-Seeing Interactive. All rights reserved.
//
// Portions are based on the ImageClient example from Apple:
// See: http://developer.apple.com/samplecode/ImageClient/listing37.html
#import <Cocoa/Cocoa.h>
#import "ASIProgressDelegate.h"
@interface ASIHTTPRequest : NSOperation {
//The url for this operation, should include get params in the query string where appropriate
NSURL *url;
//The delegate, you need to manage setting and talking to your delegate in your subclasses
id delegate;
//Parameters that will be POSTed to the url
NSMutableDictionary *postData;
//Files that will be POSTed to the url
NSMutableDictionary *fileData;
//Dictionary for custom request headers
NSMutableDictionary *requestHeaders;
//If usesKeychain is true, network requests will attempt to read credentials from the keychain, and will save them in the keychain when they are successfully presented
BOOL usesKeychain;
//When downloadDestinationPath is set, the result of this request will be downloaded to the file at this location
//If downloadDestinationPath is not set, download data will be stored in memory
NSString *downloadDestinationPath;
//Used for writing data to a file when downloadDestinationPath is set
NSOutputStream *outputStream;
//When the request fails or completes successfully, complete will be true
BOOL complete;
//If an error occurs, error will contain an NSError
NSError *error;
//If an authentication error occurs, we give the delegate a chance to handle it, ignoreError will be set to true
BOOL ignoreError;
//Username and password used for authentication
NSString *username;
NSString *password;
//Delegate for displaying upload progress (usually an NSProgressIndicator, but you can supply a different object and handle this yourself)
NSObject <ASIProgressDelegate> *uploadProgressDelegate;
//Delegate for displaying download progress (usually an NSProgressIndicator, but you can supply a different object and handle this yourself)
NSObject <ASIProgressDelegate> *downloadProgressDelegate;
// Whether we've seen the headers of the response yet
BOOL haveExaminedHeaders;
//Data we receive will be stored here
CFMutableDataRef receivedData;
//Used for sending and receiving data
CFHTTPMessageRef request;
CFReadStreamRef readStream;
// Authentication currently being used for prompting and resuming
CFHTTPAuthenticationRef authentication;
// Credentials associated with the authentication (reused until server says no)
CFMutableDictionaryRef credentials;
//Size of the response
double contentLength;
//Size of the POST payload
double postLength;
//Timer used to update the progress delegates
NSTimer *progressTimer;
//The total amount of downloaded data
double totalBytesRead;
//Realm for authentication when credentials are required
NSString *authenticationRealm;
//Called on the delegate when the request completes successfully
SEL didFinishSelector;
//Called on the delegate when the request fails
SEL didFailSelector;
//This lock will block the request until the delegate supplies authentication info
NSConditionLock *authenticationLock;
}
// Should be an HTTP or HTTPS url, may include username and password if appropriate
- (id)initWithURL:(NSURL *)newURL;
//Add a POST variable to the request
- (void)setPostValue:(id)value forKey:(NSString *)key;
//Add the contents of a local file as a POST variable to the request
- (void)setFile:(NSString *)filePath forKey:(NSString *)key;
//Add a custom header to the request
- (void)addRequestHeader:(NSString *)header value:(NSString *)value;
//the results of this request will be saved to downloadDestinationPath, if it is set
- (void)setDownloadDestinationPath:(NSString *)newDestinationPath;
- (NSString *)downloadDestinationPath;
// When set, username and password will be presented for HTTP authentication
- (void)setUsername:(NSString *)newUsername andPassword:(NSString *)newPassword;
// Delegate will get messages when the request completes, fails or when authentication is required
- (void)setDelegate:(id)newDelegate;
// Called on the delegate when the request completes successfully
- (void)setDidFinishSelector:(SEL)selector;
// Called on the delegate when the request fails
- (void)setDidFailSelector:(SEL)selector;
// upload progress delegate (usually an NSProgressIndicator) is sent information on upload progress
- (void)setUploadProgressDelegate:(id)newDelegate;
// download progress delegate (usually an NSProgressIndicator) is sent information on download progress
- (void)setDownloadProgressDelegate:(id)newDelegate;
// When true, authentication information will automatically be stored in (and re-used from) the keychain
- (void)setUsesKeychain:(BOOL)shouldUseKeychain;
// Will be true when the request is complete (success or failure)
- (BOOL)complete;
// Returns the contents of the result as an NSString (not appropriate for binary data!)
- (NSString *)dataString;
// Accessors for getting information about the request (useful for auth dialogs)
- (NSString *)authenticationRealm;
- (NSString *)host;
// Contains a description of the error that occurred if the request failed
- (NSError *)error;
// CFnetwork event handlers
- (void)handleStreamComplete;
- (void)handleStreamError;
- (void)handleBytesAvailable;
- (void)handleNetworkEvent:(CFStreamEventType)type;
// Start loading the request
- (void)loadRequest;
// Reads the response headers to find the content length, and returns true if the request needs a username and password (or if those supplied were incorrect)
- (BOOL)isAuthorizationFailure;
// Apply authentication information and resume the request after an authentication challenge
- (void)applyCredentialsAndResume;
// Unlock (unpause) the request thread so it can resume the request
// Should be called by delegates when they have populated the authentication information after an authentication challenge
- (void)retryWithAuthentication;
// Cancel loading and clean up
- (void)cancelLoad;
// Called from timer on main thread to update progress delegates
- (void)updateUploadProgress;
- (void)updateDownloadProgress;
#pragma mark keychain stuff
//Save credentials to the keychain
+ (void)saveCredentials:(NSURLCredential *)credentials forHost:(NSString *)host port:(int)port protocol:(NSString *)protocol realm:(NSString *)realm;
//Return credentials from the keychain
+ (NSURLCredential *)savedCredentialsForHost:(NSString *)host port:(int)port protocol:(NSString *)protocol realm:(NSString *)realm;
//Called when a request completes successfully
- (void)requestFinished;
//Called when a request fails
- (void)failWithProblem:(NSString *)problem;
@end
... ...
This diff is collapsed. Click to expand it.
//
// ASIProgressDelegate.h
//
// Created by Ben Copsey on 28/03/2008.
// Copyright 2008 All-Seeing Interactive. All rights reserved
//
#import <Cocoa/Cocoa.h>
@protocol ASIProgressDelegate
- (void)incrementProgress;
- (void)setDoubleValue:(double)newValue;
- (void)incrementBy:(double)amount;
- (void)setMaxValue:(double)newMax;
@end
\ No newline at end of file
... ...
//
// AppDelegate.h
//
// Created by Ben Copsey on 09/07/2008.
// Copyright 2008 All-Seeing Interactive Ltd. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@class ASIHTTPRequest;
@interface AppDelegate : NSObject {
NSOperationQueue *networkQueue;
IBOutlet NSProgressIndicator *progressIndicator;
IBOutlet NSTextView *htmlSource;
IBOutlet NSTextField *fileLocation;
IBOutlet NSWindow *window;
IBOutlet NSWindow *loginWindow;
IBOutlet NSTextField *host;
IBOutlet NSTextField *realm;
IBOutlet NSTextField *username;
IBOutlet NSTextField *password;
IBOutlet NSTextField *topSecretInfo;
IBOutlet NSButton *keychainCheckbox;
IBOutlet NSImageView *imageView1;
IBOutlet NSImageView *imageView2;
IBOutlet NSImageView *imageView3;
}
- (IBAction)simpleURLFetch:(id)sender;
- (IBAction)URLFetchWithProgress:(id)sender;
- (IBAction)fetchThreeImages:(id)sender;
- (void)authorizationNeededForRequest:(ASIHTTPRequest *)request;
- (IBAction)dismissAuthSheet:(id)sender;
- (IBAction)fetchTopSecretInformation:(id)sender;
- (IBAction)postWithProgress:(id)sender;
@end
... ...
//
// AppDelegate.m
//
// Created by Ben Copsey on 09/07/2008.
// Copyright 2008 All-Seeing Interactive Ltd. All rights reserved.
//
#import "AppDelegate.h"
#import "ASIHTTPRequest.h"
@implementation AppDelegate
- (id)init
{
[super init];
networkQueue = [[NSOperationQueue alloc] init];
return self;
}
- (void)dealloc
{
[networkQueue release];
[super dealloc];
}
- (IBAction)simpleURLFetch:(id)sender
{
ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:@"http://allseeing-i.com"]] autorelease];
[request start];
if ([request dataString]) {
[htmlSource setString:[request dataString]];
}
}
- (IBAction)URLFetchWithProgress:(id)sender
{
[networkQueue cancelAllOperations];
ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:@"http://trails-network.net/Downloads/MemexTrails_1.0b1.zip"]] autorelease];
[request setDelegate:self];
[request setDownloadProgressDelegate:progressIndicator];
[request setDidFinishSelector:@selector(URLFetchWithProgressComplete:)];
[request setDownloadDestinationPath:[[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"MemexTrails_1.0b1.zip"]];
[networkQueue addOperation:request];
}
- (void)URLFetchWithProgressComplete:(ASIHTTPRequest *)request
{
if ([request error]) {
[fileLocation setStringValue:[NSString stringWithFormat:@"An error occurred: %@",[[[request error] userInfo] objectForKey:@"Title"]]];
} else {
[fileLocation setStringValue:[NSString stringWithFormat:@"File downloaded to %@",[request downloadDestinationPath]]];
}
}
- (IBAction)fetchThreeImages:(id)sender
{
[imageView1 setImage:nil];
[imageView2 setImage:nil];
[imageView3 setImage:nil];
[networkQueue cancelAllOperations];
[progressIndicator setDoubleValue:0];
[progressIndicator setMaxValue:3];
ASIHTTPRequest *request;
request = [[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:@"http://allseeing-i.com/i/logo.png"]] autorelease];
[request setDelegate:self];
[request setDidFinishSelector:@selector(imageFetchComplete:)];
[request setDownloadDestinationPath:[[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"1.png"]];
[networkQueue addOperation:request];
request = [[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:@"http://allseeing-i.com/i/trailsnetwork.png"]] autorelease];
[request setDelegate:self];
[request setDidFinishSelector:@selector(imageFetchComplete:)];
[request setDownloadDestinationPath:[[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"2.png"]];
[networkQueue addOperation:request];
request = [[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:@"http://allseeing-i.com/i/sharedspace20.png"]] autorelease];
[request setDelegate:self];
[request setDidFinishSelector:@selector(imageFetchComplete:)];
[request setDownloadDestinationPath:[[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"3.png"]];
[networkQueue addOperation:request];
}
- (void)imageFetchComplete:(ASIHTTPRequest *)request
{
NSImage *img = [[[NSImage alloc] initWithContentsOfFile:[request downloadDestinationPath]] autorelease];
if (img) {
if ([imageView1 image]) {
if ([imageView2 image]) {
[imageView3 setImage:img];
} else {
[imageView2 setImage:img];
}
} else {
[imageView1 setImage:img];
}
}
[progressIndicator incrementBy:1];
}
- (IBAction)fetchTopSecretInformation:(id)sender
{
[networkQueue cancelAllOperations];
[progressIndicator setDoubleValue:0];
ASIHTTPRequest *request;
request = [[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:@"http://allseeing-i.com/top_secret/"]] autorelease];
[request setDelegate:self];
[request setDidFinishSelector:@selector(topSecretFetchComplete:)];
[request setUsesKeychain:[keychainCheckbox state]];
[networkQueue addOperation:request];
}
- (IBAction)topSecretFetchComplete:(ASIHTTPRequest *)request
{
if (![request error]) {
[topSecretInfo setStringValue:[request dataString]];
[topSecretInfo setFont:[NSFont boldSystemFontOfSize:13]];
}
}
- (void)authorizationNeededForRequest:(ASIHTTPRequest *)request
{
[realm setStringValue:[request authenticationRealm]];
[host setStringValue:[request host]];
[NSApp beginSheet: loginWindow
modalForWindow: window
modalDelegate: self
didEndSelector: @selector(authSheetDidEnd:returnCode:contextInfo:)
contextInfo: request];
}
- (IBAction)dismissAuthSheet:(id)sender {
[[NSApplication sharedApplication] endSheet: loginWindow returnCode: [(NSControl*)sender tag]];
}
- (void)authSheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
ASIHTTPRequest *request = (ASIHTTPRequest *)contextInfo;
if (returnCode == NSOKButton) {
[request setUsername:[[[username stringValue] copy] autorelease] andPassword:[[[password stringValue] copy] autorelease]];
[request retryWithAuthentication];
} else {
[request cancelLoad];
}
[loginWindow orderOut: self];
}
- (IBAction)postWithProgress:(id)sender
{
//Create a 1mb file
NSMutableData *data = [NSMutableData dataWithLength:1024*1024];
NSString *path = [[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"bigfile"];
[data writeToFile:path atomically:NO];
[networkQueue cancelAllOperations];
[progressIndicator setDoubleValue:0];
ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:@"http://allseeing-i.com/ignore"]] autorelease];
[request setDelegate:self];
[request setUploadProgressDelegate:progressIndicator];
[request setPostValue:@"test" forKey:@"value1"];
[request setPostValue:@"test" forKey:@"value2"];
[request setPostValue:@"test" forKey:@"value3"];
[request setFile:path forKey:@"file"];
[networkQueue addOperation:request];
}
@end
... ...
B/* Localized versions of Info.plist keys */
... ...
This diff could not be displayed because it is too large.
No preview for this file type
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIconFile</key>
<string></string>
<key>CFBundleIdentifier</key>
<string>com.allseeing-i.asi-http-request</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>NSMainNibFile</key>
<string>MainMenu</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
</dict>
</plist>
... ...
* Copyright (c) 2007-2008, All-Seeing Interactive
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of the All-Seeing Interactive nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY All-Seeing Interactive ''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 <copyright holder> 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.
\ No newline at end of file
... ...
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff was suppressed by a .gitattributes entry.
//
// Prefix header for all source files of the 'asi-http-request' target in the 'asi-http-request' project
//
#ifdef __OBJC__
#import <Cocoa/Cocoa.h>
#endif
... ...
//
// main.m
// asi-http-request
//
// Created by Ben Copsey on 09/07/2008.
// Copyright __MyCompanyName__ 2008. All rights reserved.
//
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
return NSApplicationMain(argc, (const char **) argv);
}
... ...