PageRenderTime 44ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/WebServiceDemo/Required_Libs/HTTPRequest/Mac Sample/AppDelegate.m

https://gitlab.com/praveenvelanati/ios-demo
Objective C | 456 lines | 362 code | 81 blank | 13 comment | 39 complexity | efac87ae1a6c5bdbaabc85cde679584d MD5 | raw file
  1. //
  2. // AppDelegate.m
  3. //
  4. // Created by Ben Copsey on 09/07/2008.
  5. // Copyright 2008 All-Seeing Interactive Ltd. All rights reserved.
  6. //
  7. #import "AppDelegate.h"
  8. #import "ASIHTTPRequest.h"
  9. #import "ASIFormDataRequest.h"
  10. #import "ASINetworkQueue.h"
  11. #import "ASIDownloadCache.h"
  12. #import "ASIWebPageRequest.h"
  13. @interface AppDelegate ()
  14. - (void)updateBandwidthUsageIndicator;
  15. - (void)URLFetchWithProgressComplete:(ASIHTTPRequest *)request;
  16. - (void)URLFetchWithProgressFailed:(ASIHTTPRequest *)request;
  17. - (void)imageFetch1Complete:(ASIHTTPRequest *)request;
  18. - (void)imageFetch2Complete:(ASIHTTPRequest *)request;
  19. - (void)imageFetch3Complete:(ASIHTTPRequest *)request;
  20. - (void)topSecretFetchComplete:(ASIHTTPRequest *)request;
  21. - (void)authSheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo;
  22. - (void)postFinished:(ASIHTTPRequest *)request;
  23. - (void)postFailed:(ASIHTTPRequest *)request;
  24. - (void)fetchURL:(NSURL *)url;
  25. - (void)tableViewDataFetchFinished:(ASIHTTPRequest *)request;
  26. - (void)rowImageDownloadFinished:(ASIHTTPRequest *)request;
  27. - (void)webPageFetchFailed:(ASIHTTPRequest *)request;
  28. - (void)webPageFetchSucceeded:(ASIHTTPRequest *)request;
  29. @end
  30. @implementation AppDelegate
  31. - (id)init
  32. {
  33. [super init];
  34. networkQueue = [[ASINetworkQueue alloc] init];
  35. [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateBandwidthUsageIndicator) userInfo:nil repeats:YES];
  36. return self;
  37. }
  38. - (void)dealloc
  39. {
  40. [networkQueue release];
  41. [super dealloc];
  42. }
  43. - (IBAction)simpleURLFetch:(id)sender
  44. {
  45. ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:@"http://allseeing-i.com"]] autorelease];
  46. //Customise our user agent, for no real reason
  47. [request addRequestHeader:@"User-Agent" value:@"ASIHTTPRequest"];
  48. [request setDelegate:self];
  49. [request startSynchronous];
  50. if ([request error]) {
  51. [htmlSource setString:[[request error] localizedDescription]];
  52. } else if ([request responseString]) {
  53. [htmlSource setString:[request responseString]];
  54. }
  55. }
  56. - (IBAction)URLFetchWithProgress:(id)sender
  57. {
  58. [startButton setTitle:@"Stop"];
  59. [startButton setAction:@selector(stopURLFetchWithProgress:)];
  60. NSString *tempFile = [[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"The Great American Novel.txt.download"];
  61. if ([[NSFileManager defaultManager] fileExistsAtPath:tempFile]) {
  62. [[NSFileManager defaultManager] removeItemAtPath:tempFile error:nil];
  63. }
  64. [self resumeURLFetchWithProgress:self];
  65. }
  66. - (IBAction)stopURLFetchWithProgress:(id)sender
  67. {
  68. [startButton setTitle:@"Start"];
  69. [startButton setAction:@selector(URLFetchWithProgress:)];
  70. [[self bigFetchRequest] cancel];
  71. [self setBigFetchRequest:nil];
  72. [resumeButton setEnabled:YES];
  73. }
  74. - (IBAction)resumeURLFetchWithProgress:(id)sender
  75. {
  76. [fileLocation setStringValue:@"(Request running)"];
  77. [resumeButton setEnabled:NO];
  78. [startButton setTitle:@"Stop"];
  79. [startButton setAction:@selector(stopURLFetchWithProgress:)];
  80. // Stop any other requests
  81. [networkQueue reset];
  82. [self setBigFetchRequest:[ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/redirect_resume"]]];
  83. [[self bigFetchRequest] setDownloadDestinationPath:[[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"The Great American Novel.txt"]];
  84. [[self bigFetchRequest] setTemporaryFileDownloadPath:[[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"The Great American Novel.txt.download"]];
  85. [[self bigFetchRequest] setAllowResumeForFileDownloads:YES];
  86. [[self bigFetchRequest] setDelegate:self];
  87. [[self bigFetchRequest] setDidFinishSelector:@selector(URLFetchWithProgressComplete:)];
  88. [[self bigFetchRequest] setDidFailSelector:@selector(URLFetchWithProgressFailed:)];
  89. [[self bigFetchRequest] setDownloadProgressDelegate:progressIndicator];
  90. [[self bigFetchRequest] startAsynchronous];
  91. }
  92. - (void)URLFetchWithProgressComplete:(ASIHTTPRequest *)request
  93. {
  94. [fileLocation setStringValue:[NSString stringWithFormat:@"File downloaded to %@",[request downloadDestinationPath]]];
  95. [startButton setTitle:@"Start"];
  96. [startButton setAction:@selector(URLFetchWithProgress:)];
  97. }
  98. - (void)URLFetchWithProgressFailed:(ASIHTTPRequest *)request
  99. {
  100. if ([[request error] domain] == NetworkRequestErrorDomain && [[request error] code] == ASIRequestCancelledErrorType) {
  101. [fileLocation setStringValue:@"(Request paused)"];
  102. } else {
  103. [fileLocation setStringValue:[NSString stringWithFormat:@"An error occurred: %@",[[request error] localizedDescription]]];
  104. [startButton setTitle:@"Start"];
  105. [startButton setAction:@selector(URLFetchWithProgress:)];
  106. }
  107. }
  108. - (IBAction)fetchThreeImages:(id)sender
  109. {
  110. [imageView1 setImage:nil];
  111. [imageView2 setImage:nil];
  112. [imageView3 setImage:nil];
  113. [networkQueue reset];
  114. [networkQueue setDownloadProgressDelegate:progressIndicator];
  115. [networkQueue setDelegate:self];
  116. [networkQueue setShowAccurateProgress:([showAccurateProgress state] == NSOnState)];
  117. ASIHTTPRequest *request;
  118. request = [[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/images/small-image.jpg"]] autorelease];
  119. [request setDownloadDestinationPath:[[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"1.png"]];
  120. [request setDownloadProgressDelegate:imageProgress1];
  121. [request setDidFinishSelector:@selector(imageFetch1Complete:)];
  122. [request setDelegate:self];
  123. [networkQueue addOperation:request];
  124. request = [[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/images/medium-image.jpg"]] autorelease];
  125. [request setDownloadDestinationPath:[[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"2.png"]];
  126. [request setDownloadProgressDelegate:imageProgress2];
  127. [request setDidFinishSelector:@selector(imageFetch2Complete:)];
  128. [request setDelegate:self];
  129. [networkQueue addOperation:request];
  130. request = [[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/images/large-image.jpg"]] autorelease];
  131. [request setDownloadDestinationPath:[[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"3.png"]];
  132. [request setDownloadProgressDelegate:imageProgress3];
  133. [request setDidFinishSelector:@selector(imageFetch3Complete:)];
  134. [request setDelegate:self];
  135. [networkQueue addOperation:request];
  136. [networkQueue go];
  137. }
  138. - (void)updateBandwidthUsageIndicator
  139. {
  140. [bandwidthUsed setStringValue:[NSString stringWithFormat:@"%luKB / second",[ASIHTTPRequest averageBandwidthUsedPerSecond]/1024]];
  141. }
  142. - (IBAction)throttleBandwidth:(id)sender
  143. {
  144. if ([(NSButton *)sender state] == NSOnState) {
  145. [ASIHTTPRequest setMaxBandwidthPerSecond:ASIWWANBandwidthThrottleAmount];
  146. } else {
  147. [ASIHTTPRequest setMaxBandwidthPerSecond:0];
  148. }
  149. }
  150. - (void)imageFetch1Complete:(ASIHTTPRequest *)request
  151. {
  152. NSImage *img = [[[NSImage alloc] initWithContentsOfFile:[request downloadDestinationPath]] autorelease];
  153. if (img) {
  154. [imageView1 setImage:img];
  155. }
  156. }
  157. - (void)imageFetch2Complete:(ASIHTTPRequest *)request
  158. {
  159. NSImage *img = [[[NSImage alloc] initWithContentsOfFile:[request downloadDestinationPath]] autorelease];
  160. if (img) {
  161. [imageView2 setImage:img];
  162. }
  163. }
  164. - (void)imageFetch3Complete:(ASIHTTPRequest *)request
  165. {
  166. NSImage *img = [[[NSImage alloc] initWithContentsOfFile:[request downloadDestinationPath]] autorelease];
  167. if (img) {
  168. [imageView3 setImage:img];
  169. }
  170. }
  171. - (IBAction)fetchTopSecretInformation:(id)sender
  172. {
  173. [networkQueue reset];
  174. [progressIndicator setDoubleValue:0];
  175. ASIHTTPRequest *request;
  176. request = [[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:@"http://allseeing-i.com/top_secret/"]] autorelease];
  177. [request setDidFinishSelector:@selector(topSecretFetchComplete:)];
  178. [request setDelegate:self];
  179. [request setUseKeychainPersistence:[keychainCheckbox state]];
  180. [request startAsynchronous];
  181. }
  182. - (void)topSecretFetchComplete:(ASIHTTPRequest *)request
  183. {
  184. if (![request error]) {
  185. [topSecretInfo setStringValue:[request responseString]];
  186. [topSecretInfo setFont:[NSFont boldSystemFontOfSize:13]];
  187. }
  188. }
  189. - (void)authenticationNeededForRequest:(ASIHTTPRequest *)request
  190. {
  191. [realm setStringValue:[request authenticationRealm]];
  192. [host setStringValue:[[request url] host]];
  193. [NSApp beginSheet: loginWindow
  194. modalForWindow: window
  195. modalDelegate: self
  196. didEndSelector: @selector(authSheetDidEnd:returnCode:contextInfo:)
  197. contextInfo: request];
  198. }
  199. - (void)proxyAuthenticationNeededForRequest:(ASIHTTPRequest *)request
  200. {
  201. [realm setStringValue:[request proxyAuthenticationRealm]];
  202. [host setStringValue:[request proxyHost]];
  203. [NSApp beginSheet: loginWindow
  204. modalForWindow: window
  205. modalDelegate: self
  206. didEndSelector: @selector(authSheetDidEnd:returnCode:contextInfo:)
  207. contextInfo: request];
  208. }
  209. - (IBAction)dismissAuthSheet:(id)sender {
  210. [[NSApplication sharedApplication] endSheet: loginWindow returnCode: [(NSControl*)sender tag]];
  211. }
  212. - (void)authSheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
  213. {
  214. ASIHTTPRequest *request = (ASIHTTPRequest *)contextInfo;
  215. if (returnCode == NSOKButton) {
  216. if ([request authenticationNeeded] == ASIProxyAuthenticationNeeded) {
  217. [request setProxyUsername:[[[username stringValue] copy] autorelease]];
  218. [request setProxyPassword:[[[password stringValue] copy] autorelease]];
  219. } else {
  220. [request setUsername:[[[username stringValue] copy] autorelease]];
  221. [request setPassword:[[[password stringValue] copy] autorelease]];
  222. }
  223. [request retryUsingSuppliedCredentials];
  224. } else {
  225. [request cancelAuthentication];
  226. }
  227. [loginWindow orderOut: self];
  228. }
  229. - (IBAction)postWithProgress:(id)sender
  230. {
  231. //Create a 1MB file
  232. NSMutableData *data = [NSMutableData dataWithLength:1024*1024];
  233. NSString *path = [[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"bigfile"];
  234. [data writeToFile:path atomically:NO];
  235. [networkQueue reset];
  236. [networkQueue setShowAccurateProgress:YES];
  237. [networkQueue setUploadProgressDelegate:progressIndicator];
  238. [networkQueue setRequestDidFailSelector:@selector(postFailed:)];
  239. [networkQueue setRequestDidFinishSelector:@selector(postFinished:)];
  240. [networkQueue setDelegate:self];
  241. ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:@"http://allseeing-i.com/ignore"]] autorelease];
  242. [request setPostValue:@"test" forKey:@"value1"];
  243. [request setPostValue:@"test" forKey:@"value2"];
  244. [request setPostValue:@"test" forKey:@"value3"];
  245. [request setFile:path forKey:@"file"];
  246. [networkQueue addOperation:request];
  247. [networkQueue go];
  248. }
  249. - (void)postFinished:(ASIHTTPRequest *)request
  250. {
  251. [postStatus setStringValue:@"Post Finished"];
  252. }
  253. - (void)postFailed:(ASIHTTPRequest *)request
  254. {
  255. [postStatus setStringValue:[NSString stringWithFormat:@"Post Failed: %@",[[request error] localizedDescription]]];
  256. }
  257. - (IBAction)reloadTableData:(id)sender
  258. {
  259. [[self tableQueue] cancelAllOperations];
  260. [self setRowData:[NSMutableArray array]];
  261. [tableView reloadData];
  262. [self setTableQueue:[ASINetworkQueue queue]];
  263. ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/table-row-data.xml"]];
  264. [request setDownloadCache:[ASIDownloadCache sharedCache]];
  265. [request setDidFinishSelector:@selector(tableViewDataFetchFinished:)];
  266. [request setDelegate:self];
  267. [[self tableQueue] addOperation:request];
  268. [[self tableQueue] setDownloadProgressDelegate:progressIndicator];
  269. [[self tableQueue] go];
  270. }
  271. - (void)tableViewDataFetchFailed:(ASIHTTPRequest *)request
  272. {
  273. if ([[request error] domain] != NetworkRequestErrorDomain || ![[request error] code] == ASIRequestCancelledErrorType) {
  274. [tableLoadStatus setStringValue:@"Loading data failed"];
  275. }
  276. }
  277. - (void)tableViewDataFetchFinished:(ASIHTTPRequest *)request
  278. {
  279. NSXMLDocument *xml = [[[NSXMLDocument alloc] initWithData:[request responseData] options:NSXMLDocumentValidate error:nil] autorelease];
  280. for (NSXMLElement *row in [[xml rootElement] elementsForName:@"row"]) {
  281. NSMutableDictionary *rowInfo = [NSMutableDictionary dictionary];
  282. NSString *description = [[[row elementsForName:@"description"] objectAtIndex:0] stringValue];
  283. [rowInfo setValue:description forKey:@"description"];
  284. NSString *imageURL = [[[row elementsForName:@"image"] objectAtIndex:0] stringValue];
  285. ASIHTTPRequest *imageRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:imageURL]];
  286. [imageRequest setDownloadCache:[ASIDownloadCache sharedCache]];
  287. [imageRequest setDidFinishSelector:@selector(rowImageDownloadFinished:)];
  288. [imageRequest setDidFailSelector:@selector(tableViewDataFetchFailed:)];
  289. [imageRequest setDelegate:self];
  290. [imageRequest setUserInfo:rowInfo];
  291. [[self tableQueue] addOperation:imageRequest];
  292. [[self rowData] addObject:rowInfo];
  293. }
  294. [tableView reloadData];
  295. }
  296. - (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
  297. {
  298. return [[self rowData] count];
  299. }
  300. - (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
  301. {
  302. if ([[aTableColumn identifier] isEqualToString:@"image"]) {
  303. return [[[self rowData] objectAtIndex:rowIndex] objectForKey:@"image"];
  304. } else {
  305. return [[[self rowData] objectAtIndex:rowIndex] objectForKey:@"description"];
  306. }
  307. }
  308. - (void)rowImageDownloadFinished:(ASIHTTPRequest *)request
  309. {
  310. NSImage *image = [[[NSImage alloc] initWithData:[request responseData]] autorelease];
  311. [(NSMutableDictionary *)[request userInfo] setObject:image forKey:@"image"];
  312. [tableView reloadData]; // Not efficient, but I hate table view programming :)
  313. }
  314. - (IBAction)clearCache:(id)sender
  315. {
  316. [[ASIDownloadCache sharedCache] clearCachedResponsesForStoragePolicy:ASICacheForSessionDurationCacheStoragePolicy];
  317. [[ASIDownloadCache sharedCache] clearCachedResponsesForStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
  318. }
  319. - (IBAction)fetchWebPage:(id)sender
  320. {
  321. [self fetchURL:[NSURL URLWithString:[urlField stringValue]]];
  322. }
  323. - (void)webView:(WebView *)sender decidePolicyForNavigationAction:(NSDictionary *)actionInformation request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id)listener
  324. {
  325. // If this is a web page we've requested ourselves, let it load
  326. if ([[actionInformation objectForKey:WebActionNavigationTypeKey] intValue] == WebNavigationTypeOther) {
  327. [listener use];
  328. return;
  329. }
  330. // If the user clicked on a link, let's tell the webview to ignore it, and we'll load it ourselves
  331. [self fetchURL:[NSURL URLWithString:[[request URL] absoluteString] relativeToURL:[NSURL URLWithString:[urlField stringValue]]]];
  332. [listener ignore];
  333. }
  334. - (void)fetchURL:(NSURL *)url
  335. {
  336. ASIWebPageRequest *request = [ASIWebPageRequest requestWithURL:url];
  337. [request setDidFailSelector:@selector(webPageFetchFailed:)];
  338. [request setDidFinishSelector:@selector(webPageFetchSucceeded:)];
  339. [request setDelegate:self];
  340. [request setShowAccurateProgress:NO];
  341. [request setDownloadProgressDelegate:progressIndicator];
  342. [request setUrlReplacementMode:([dataURICheckbox state] == NSOnState ? ASIReplaceExternalResourcesWithData : ASIReplaceExternalResourcesWithLocalURLs)];
  343. // It is strongly recommended that you set both a downloadCache and a downloadDestinationPath for all ASIWebPageRequests
  344. [request setDownloadCache:[ASIDownloadCache sharedCache]];
  345. [request setDownloadDestinationPath:[[ASIDownloadCache sharedCache] pathToStoreCachedResponseDataForRequest:request]];
  346. [[ASIDownloadCache sharedCache] setShouldRespectCacheControlHeaders:NO];
  347. [request startAsynchronous];
  348. }
  349. - (void)webPageFetchFailed:(ASIHTTPRequest *)request
  350. {
  351. [[NSAlert alertWithError:[request error]] runModal];
  352. }
  353. - (void)webPageFetchSucceeded:(ASIHTTPRequest *)request
  354. {
  355. NSURL *baseURL;
  356. if ([dataURICheckbox state] == NSOnState) {
  357. baseURL = [request url];
  358. // If we're using ASIReplaceExternalResourcesWithLocalURLs, we must set the baseURL to point to our locally cached file
  359. } else {
  360. baseURL = [NSURL fileURLWithPath:[request downloadDestinationPath]];
  361. }
  362. if ([request downloadDestinationPath]) {
  363. NSString *response = [NSString stringWithContentsOfFile:[request downloadDestinationPath] encoding:[request responseEncoding] error:nil];
  364. [webPageSource setString:response];
  365. [[webView mainFrame] loadHTMLString:response baseURL:baseURL];
  366. } else if ([request responseString]) {
  367. [webPageSource setString:[request responseString]];
  368. [[webView mainFrame] loadHTMLString:[request responseString] baseURL:baseURL];
  369. }
  370. [urlField setStringValue:[[request url] absoluteString]];
  371. }
  372. @synthesize bigFetchRequest;
  373. @synthesize rowData;
  374. @synthesize tableQueue;
  375. @end