IOS development-Ios network programming synchronous get Method Request Programming

Source: Internet
Author: User

The ios sdk provides two different APIs for synchronous and asynchronous requests for HTTP requests. You can also use get or post methods. First, we will understand the simplest synchronous GET request.

To learn how to use these APIs, The mynotes "Memorandum" application instance uses data from the server rather than local notes. XML (or notes. JSON) files.

First, the query service can be implemented in the masterviewcontroller class of the master View Controller. The masterviewcontroller. H code is as follows:

# Import <uikit/uikit. h> # import "nsstring + urlencoding. H "# import" nsnumber + message. h "@ interface masterviewcontroller: uitableviewcontroller @ property (strong, nonatomic) detailviewcontroller * detailviewcontroller; // Save the data list @ property (nonatomic, strong) nsmutablearray * listdata; // reload table view-(void) reloadview :( nsdictionary *) RES; // start to request web service-(void) startrequest; @ end

 

 

The introduction of the header file nsstring + urlencoding. H requires URL encoding in the program. Introducing the header file nsnumber + message. h is used to convert the code returned by the server into messages that you can understand. The main code in masterviewcontroller. m is as follows:

- (void)viewDidLoad{[super viewDidLoad];self.navigationItem.leftBarButtonItem = self.editButtonItem;self.detailViewController  = (DetailViewController *)[[self.splitViewController.viewControllers lastObject] topViewController];[self startRequest];                                                ①} #pragma mark – Table View- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {return 1;} - (NSInteger)tableView:(UITableView *)tableViewnumberOfRowsInSection:(NSInteger)section {return self.listData.count;} - (UITableViewCell *)tableView:(UITableView *)tableViewcellForRowAtIndexPath:(NSIndexPath *)indexPath {UITableViewCell *cell= [tableView dequeueReusableCellWithIdentifier:@"Cell"forIndexPath:indexPath];NSMutableDictionary*  dict = self.listData[indexPath.row];cell.textLabel.text = [dict objectForKey:@"Content"];cell.detailTextLabel.text = [dict objectForKey:@"CDate"];return cell;}

 

 

The code line ① [self startrequest] calls its own method startrequest to request web service. The startrequest method code in masterviewcontroller. m is as follows:

/** Start to request Web Service */-(void) startrequest {nsstring * strurl = [[nsstring alloc] initwithformat: @ "http: // iosbook3/mynotes/WebService. php? Email =%@ & type =%@ & Action =%@ ", @" <your iosbook1.com user email address> ", @" JSON ", @" Query "]; ① nsurl * url = [nsurl urlwithstring: [strurl urlencodedstring]; ② nsurlrequest * request = [[nsurlrequest alloc] initwithurl: url]; ③ nsdata * Data = [nsurlconnection sendsynchronousrequest: requestreturningresponse: Nil error: Nil]; ④ nslog (@ "request completed ..."); Nsdictionary * resdict = [nsjsonserialization jsonobjectwithdata: dataoptions: nsjsonreadingallowfragments error: Nil]; [self reloadview: resdict]; ⑤}

 

 

In addition, we also mentioned a classification nsstring (urlencoding). Its function is to encode and decode the URL. Its code is as follows:

@interface NSString (URLEncoding) -(NSString *)URLEncodedString;-(NSString *)URLDecodedString; @end @implementation NSString (URLEncoding) - (NSString *)URLEncodedString{NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,①(CFStringRef)self,NULL,                           ②CFSTR(“+$,#[] “),                      ③kCFStringEncodingUTF8));return result;}- (NSString*)URLDecodedString{NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault,                                                 ③(CFStringRef)self, CFSTR(“”),                                       ④kCFStringEncodingUTF8));return result;}@end

 

 

The cfurlcreatestringbyaddingpercentescape function is a C function provided by the core foundation framework. It can convert the content into URL encoding. The line ② parameter specifies the character set that does not encode the invalid URL character, for example, "! . The line ③ parameter combines the character sets that must be encoded as valid URL characters.

Line ③ cfurlcreatestringbyreplacingpercentescapesusingencoding is a C function provided by the core foundation framework. It is opposite to the above cfurlcreatestringbyaddingpercentescape function and implements URL Decoding. The parameter in line ④ specifies the character set that is not decoded.

The foundation framework also provides the objective-C-based method for URL encoding and decoding. The nsstring method corresponding to the cfurlcreatestringbyaddingpercentescape function is stringbyaddingpercentescapesusingencoding. The nsstring method corresponding to the cfurlcreatestringbyreplacingpercentescapesusingencoding function is stringbyreplacingpercentescapesusingencoding. Since these methods cannot customize whether to encode or decode character sets, there is no flexibility in the above function.

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.