Network request, ios network request

Source: Internet
Author: User
Tags file url

Network request, ios network request
Directly run the Code:

/// TableViewController. m /// # import "TableViewController. h "@ interface TableViewController () <NSURLConnectionDataDelegate> @ property (nonatomic, retain) NSMutableData * receivedData; // variable binary byte stream attribute, used to save data transmitted by the server. @ Property (nonatomic, retain) UIImageView * imageView; @ end @ implementation TableViewController-(void) dealloc {[_ receivedData release]; [_ imageView release]; [super dealloc];} -(NSMutableData *) receivedData {if (! _ ReceivedData) {self. receivedData = [NSMutableData data];} return _ receivedData;}-(UIImageView *) imageView {if (! _ ImageView) {self. imageView = [[UIImageView alloc] initWithFrame: CGRectMake (0, 0,300,200)]; _ imageView. center = self. view. center; [self. view addSubview: _ imageView];} return _ imageView;}-(void) viewDidLoad {[super viewDidLoad]; // 1. Convert the URL string to an NSURL object. Note: the url requires a prefix, for example: http: // ftp: // https: // NSURL * url = [NSURL URLWithString: @ "http://m2.qiushibaike.com/article/list/text? Count = 3 & page = 1 & AdID = 14314020462881C8509990 "]; NSURL * url = [NSURL URLWithString: @" http://project.lanou3g.com/teacher/duke/getAndPostRequest.php "]; NSLog (@" % @ ", url ); // file URL. A file path string must be provided when a URL object is created. This URL automatically adds file: // prefix // NSURL * fileUrl = [NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource: @ "beutifuly" ofType: @ "jpg"]; // NSLog (@ "% @", fileUrl ); // 2. Create NSURLRequest Based on the specified NSURL object Evaluate the object NSURLRequest * request = [NSURLRequest requestWithURL: url]; // variable request object: * mutableRequest = [NSMutableURLRequest requestWithURL: url cachePolicy: expires timeoutInterval: 60]; // if it is a Post request, you need to create a request using the subclass mutableRequest. // you can set the Request Method to POST. The default request is GET mutableRequest. HTTPMethod = @ "POST"; mutableRequest. HTTPBody = [@ "paramdid logo.png" dataUsingEncod Ing: NSUTF8StringEncoding]; // NSURLConnection * connection = [NSURLConnection connectionWithRequest: request delegate: self]; NSURLConnection * connection = [NSURLConnection connectionWithRequest: mutableRequest delegate: self]; NSURLResponse * response = nil; NSError * error = nil; NSData * receivedData = [NSURLConnection sendSynchronousRequest: request returningResponse: & response error: & error]; // NSLog (@" % @ ", Response); // NSLog (@" % @ ", error); // once a synchronization link is established, it can be completed only when data transmission is completed or an error occurs, otherwise, the main thread will wait until the data transmission is complete, and it is easy to see that user operations cannot get the response of the main thread stuck. In a large amount of data transmission, do not use synchronous connection requests // asynchronous connection requests to open sub-threads and add them to the operation queue when a link is established, if the server makes the response object with the corresponding block parameter response, if the data download is complete, the data is the corresponding data. If an error occurs, the error information is stored in the error, asynchronous, also known as non-synchronous, means that if the main thread encounters a network request during operation, it will open up a sub-thread to load data. After the sub-thread completes data transmission, data is transmitted to the main thread in the form of blocks, and the main thread is parsed and displayed. [NSURLConnection failed: request queue: [inclumainqueue] completionHandler: ^ (NSURLResponse * response, NSData * data, NSError * connectionError) {NSString * content = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding] autorelding]; // NSLog (@ "% @", content); NSArray * items = [[NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainer S error: nil] objectForKey: @ "items"]; // NSLog (@ "% @", items) ;}] ;}- (void) didReceiveMemoryWarning {[super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated .} -(void) connection :( NSURLConnection *) connection didReceiveResponse :( NSURLResponse *) response {NSLog (@ "link request to get Server response % s", _ FUNCTION __); NSLog (@ "% @", response);}-(void) connection :( NSURLConnection *) connection DidReceiveData :( NSData *) data {NSLog (@ "continuously get the data packet transmitted by the server % s", _ FUNCTION _); // NSLog (@ "% @", data); // use data [self. receivedData appendData: data]; NSLog (@ "% ld", self. receivedData. length); // NSLog (@ "% @", [[NSString alloc] initWithData: self. receivedData encoding: NSUTF8StringEncoding]); // NSDictionary * dict = [NSJSONSerialization JSONObjectWithData: self. receivedData options: NSJSONReadingMutable Containers error: nil]; // NSLog (@ "% @", dict); // sets imageView as a global variable and displays the entire image slowly. UIImage * image = [UIImage imageWithData: self. receivedData]; self. imageView. image = image;}-(void) connectionDidFinishLoading :( NSURLConnection *) connection {NSLog (@ "packet transfer completed % s", _ FUNCTION __); // UIImage * image = [UIImage imageWithData: self. receivedData]; // UIImageView * imageView = [[UIImageView alloc] initWithFrame: CGRectMake (0, 0,300,200)]; // imageView. image = image; // imageView. center = self. view. center; // [self. view addSubview: imageView]; // [imageView release];}-(void) connection :( NSURLConnection *) connection didFailWithError :( NSError *) error {NSLog (@ "Data Transmission failed, error % s ", _ FUNCTION _) ;}# pragma mark-Table view data source-(NSInteger) numberOfSectionsInTableView :( UITableView *) tableView {return 0 ;} -(NSInteger) tableView :( UITableView *) tableView numberOfRowsInSection :( NSInteger) section {return 0;}/*-(UITableViewCell *) tableView :( UITableView *) tableView cellForRowAtIndexPath :( NSIndexPath *) indexPath {UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier: <# @ "reuseIdentifier" #> forIndexPath: indexPath]; // Configure the cell... return cell;} * // Override to support conditional editing of the table view. -(BOOL) tableView :( UITableView *) tableView canEditRowAtIndexPath :( NSIndexPath *) indexPath {// Return NO if you do not want the specified item to be editable. return YES;} * // Override to support editing the table view. -(void) tableView :( UITableView *) tableView commitEditingStyle :( UITableViewCellEditingStyle) editingStyle forRowAtIndexPath :( NSIndexPath *) indexPath {if (editingStyle = UITableViewCellEditingStyleDelete) {// Delete the row from the data source [tableView deleteRowsAtIndexPaths: @ [indexPath] withRowAnimation: UITableViewRowAnimationFade];} else if (editingStyle = UITableViewCellEditingStyleInsert) {// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view} * // Override to support rearranging the table view. -(void) tableView :( UITableView *) tableView moveRowAtIndexPath :( NSIndexPath *) fromIndexPath toIndexPath :( NSIndexPath *) toIndexPath {} * // Override to support conditional rearranging of the table view. -(BOOL) tableView :( UITableView *) tableView canMoveRowAtIndexPath :( NSIndexPath *) indexPath {// Return NO if you do not want the item to be re-orderable. return YES;} * // * # pragma mark-Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation-(void) prepareForSegue :( UIStoryboardSegue *) segue sender :( id) sender {// Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller .} * // @ end

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.