summaryrefslogtreecommitdiffstats
path: root/Classes/Fetcher.m
blob: 6e3e7b3bd595674ad32f62ecffe61a9887ff1113 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//
//  Fetcher.m
//  PicCast
//
//  Created by Matthew Handler on 4/26/11.
//  Copyright 2011 Earl Industries. All rights reserved.
//

#import "Fetcher.h"
#import "PicCastAppDelegate.h"

@implementation Fetcher

@synthesize delegate, payload;

+ (Fetcher *) initWithString:(NSString *)string andDelegate:(id<FetcherDelegate>)d {
	return [Fetcher initWithString:string payload:nil andDelegate:d];
}

+ (Fetcher *) initWithString:(NSString *)string payload:(id)p andDelegate:(id <FetcherDelegate>)d {
	Fetcher *fetcher = [[[Fetcher alloc] init] autorelease];
	fetcher.delegate = d;
	if (payload != nil) fetcher.payload = p; 
	[fetcher setUrlAndConnect:string];
	return fetcher;
}

- (Fetcher *) init {
	receivedData = [[NSMutableData data] retain];
	return self;
}

- (void) setUrlAndConnect:(NSString *)string {
	
	NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:string]
											  cachePolicy:NSURLRequestUseProtocolCachePolicy
										  timeoutInterval:30.0];	
	if ([NSURLConnection connectionWithRequest:theRequest delegate:self]) {
		[receivedData setLength:0];
	} else {
		[PicCastAppDelegate prompt:@"Error" withMessage:@"No internet connection" andButtonTitle:@"shucks" withDelegate:self];		
	}		
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [receivedData setLength:0];	
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [receivedData appendData:data];	
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	if (payload != nil && [(NSObject *)delegate respondsToSelector:@selector(connection:failedWithError:andPayload:)]) 
		[delegate connection:connection failedWithError:error andPayload:payload];
	else
		[delegate connection:connection failedWithError:error];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {	
	if (payload != nil && [(NSObject *)delegate respondsToSelector:@selector(connection:finishedWithData:andPayload:)]) 
		[delegate connection:connection finishedWithData:receivedData andPayload:payload];
	else
		[delegate connection:connection finishedWithData:receivedData];
}

- (void) dealloc {
	[receivedData release];
	[super dealloc];
}

@end