WebServices solution for iPhone - First Stage
- (FileDownload *) initWithURL:(NSString *)url callBack:(id<FileDownloadProtocol>)delegate;
/**
Initialize with file to download
**/
- (FileDownload *)initWithURL:(NSString *)url callBack:(id<FileDownloadProtocol>)delegate
{
[self init];
[self startDownloadFile:url callBack:delegate];
return self;
}
- (void)startDownloadFile:(NSString *)url callBack:(id<FileDownloadProtocol>)delegate;
/**
Call to download file
**/
- (void)startDownloadFile:(NSString *)url callBack:(id<FileDownloadProtocol>)delegate
{
processing = YES;
callBackObject = delegate;
NSURLRequest *xmlURLRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
self.dataFeedConnection = [[[NSURLConnection alloc] initWithRequest:xmlURLRequest delegate:self] autorelease];
if (self.dataFeedConnection == nil)
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:NSLocalizedString(@"No Connection Error", @"Error message displayed when not connected to the Internet.") forKey:NSLocalizedDescriptionKey];
NSError *noConnectionError = [NSError errorWithDomain:NSCocoaErrorDomain code:kCFURLErrorNotConnectedToInternet userInfo:userInfo];
[self handleError:noConnectionError];
}
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
-(void)stopDownload;
/**
Stop actual download process
**/
-(void)stopDownload
{
processing = NO;
if (dataFeedConnection != nil)
{
[dataFeedConnection cancel];
}
}
@property (nonatomic, assign) int jobID;
@protocol FileDownloadProtocol
/**
Notify an error
**/
- (void) downloadError:(NSError *)error downloadID:(NSInteger)jobID;
/**
Notify download complete
**/
- (void) downloadSucceed:(NSMutableData *)data downloadID:(NSInteger)jobID;
@end
- (void) downloadError:(NSError *)error downloadID:(NSInteger)jobID;
- (void)handleError:(NSError *)error
{
if (processing && callBackObject != nil)
{
// Call the error Callback
[callBackObject downloadError:error downloadID:jobID];
}
}
- (void) downloadSucceed:(NSMutableData *)data downloadID:(NSInteger)jobID;
/**
Connection finishes
**/
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
self.dataFeedConnection = nil;
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
if (processing && callBackObject != nil)
{
// Call the Succeed Callback
[callBackObject downloadSucceed:dataData downloadID:jobID];
}
self.dataData = nil;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
self.downloadObject = [[FileDownload alloc] init];
[self.downloadObject setJobID:theID];
[self.downloadObject startDownloadFile:theURL callBack:self];
Comments