// // ViewController.h // NSURLConnectionApp // // Created by Weerachai on 12/8/55 BE. // Copyright (c) 2555 Weerachai. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController { IBOutlet UIImageView *imgView; IBOutlet UIActivityIndicatorView *loading; } @property(nonatomic,assign) NSMutableData *receivedData; @end
// // ViewController.m // NSURLConnectionApp // // Created by Weerachai on 12/8/55 BE. // Copyright (c) 2555 Weerachai. All rights reserved. // #import "ViewController.h" @interface ViewController () @end @implementation ViewController @synthesize receivedData; - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.thaicreate.com/url/girl.jpg"] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0]; NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; [loading startAnimating]; if (theConnection) { self.receivedData = nil; } else { UIAlertView *connectFailMessage = [[UIAlertView alloc] initWithTitle:@"NSURLConnection " message:@"Failed in viewDidLoad" delegate: self cancelButtonTitle:@"Ok" otherButtonTitles: nil]; [connectFailMessage show]; [connectFailMessage release]; } } - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { receivedData = [[NSMutableData alloc] init]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { sleep(1); [receivedData appendData:data]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { [connection release]; [receivedData release]; // inform the user UIAlertView *didFailWithErrorMessage = [[UIAlertView alloc] initWithTitle: @"NSURLConnection " message: @"didFailWithError" delegate: self cancelButtonTitle: @"Ok" otherButtonTitles: nil]; [didFailWithErrorMessage show]; [didFailWithErrorMessage release]; //inform the user NSLog(@"Connection failed! Error - %@", [error localizedDescription]); } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { if(receivedData) { NSLog(@"%@",receivedData); UIImage *image = [[UIImage alloc] initWithData:receivedData]; //self.image = image; [self performSelectorOnMainThread:@selector(setImageView:) withObject:image waitUntilDone:YES]; [image release]; [loading stopAnimating]; [loading setHidden:TRUE]; } // release the connection, and the data object [connection release]; [receivedData release]; } // Display Image - (void) setImageView:(UIImage *) img { imgView.image = img; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (void)dealloc { [imgView release]; [loading release]; [super dealloc]; } @end
ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท