iOS Development-afnetworking/nsurlsession Asynchronous processing

Source: Internet
Author: User

I believe that the famous afnetworking API on GitHub must be a stranger. This article is a basic use of the experience, the veteran please detour.

Afnetworking and Nsurlsession rely on the code in the block to get the network data (such as by JSON format), the advantage is not to block the process of the host column, when the code inside the block is completed, callback processing, Back to the home row. This way, when a lot of network data is needed, it will not allow the user to wait for a long time on a blank page, and can load the part that does not need the network data and increase the user experience. And now nsurlconnection this method of operation in the main queue has been deprecated, try to use both of these asynchronous processing methods.

The following is a sample code for afnetworking (using JSON format, source itunes RSS top songs)

1 #import "FetchData.h"2 #import<AFNetworking/AFNetworking.h>3 4 @implementationFetchdata5 6- (void) Fetchdata7 {8Self.resultarray =[[Nsmutablearray alloc]init];9Afhttprequestoperationmanager *manager =[[Afhttprequestoperationmanager alloc]init];Ten[Manager GET:@"Https://itunes.apple.com/us/rss/topsongs/limit=10/json"Parameters:nil success:^ (afhttprequestoperation * _nonnull operation, Nsdictionary *responseobject) { OneNsdictionary *feed = [Responseobject objectforkey:@"Feed"]; ANsarray *entry = [Feed Objectforkey:@"entry"]; -          for(Nsdictionary *detaildictinchentry) { -[Self.resultarray addobject:[detaildict Valueforkeypath:@"Title.label"]]; the         } -[[Nsnotificationcenter Defaultcenter]postnotificationname:@"Reload" Object: self]; -          -          +} failure:^ (Afhttprequestoperation * _nonnull operation, Nserror *_nonnull Error) { -NSLog (@"%@", [error description]); +     }]; A}

About the import afnetworking API, link https://github.com/AFNetworking/AFNetworking

1- (void) Fetchsessiondata2 {3Self.resultarray =[[Nsmutablearray alloc]init];4Nsurlsession *session =[Nsurlsession sharedsession];5Nsurl *url = [Nsurl urlwithstring:@"Https://itunes.apple.com/us/rss/topsongs/limit=10/json"];6Nsurlrequest *request =[Nsurlrequest Requestwithurl:url];7Nsurlsessiondatatask *datatask = [Session datataskwithrequest:request completionhandler:^ (NSData * _Nullable data, Nsurlresponse * _nullable response, Nserror *_nullable Error) {8Nsdictionary *json = [nsjsonserialization jsonobjectwithdata:data options:0Error:nil];9Nsdictionary *feed = [JSON objectforkey:@"Feed"];TenNsarray *entry = [Feed Objectforkey:@"entry"]; One          for(Nsdictionary *detaildictinchentry) { A[Self.resultarray addobject:[detaildict Valueforkeypath:@"Title.label"]]; -              -         } the[[Nsnotificationcenter Defaultcenter]postnotificationname:@"Reload" Object: self]; -     }]; - [Datatask resume]; -}

[[Nsnotificationcenter Defaultcenter]postnotificationname:@ "reload"object: Self];

Is the key, because it is asynchronous processing, so we do not know when the contents of the block will be completed, because the example under the MVC structure, so use [nsnotificationcenter] to monitor block execution, if the method is in a Viewcontroller, Replace the code with [Self.tableview Reloaddata];

Here is the reason, because the Uikit control is based on the existence of the viewcontroller, even if the property is changed to strong, will still be release after this viewcontroller disappears, so if it is an MVC structure, in the model file, Even if you initialize an instance of Viewcontroller and make it TableView Reloaddata, returning the Viewcontroller again, the TableView will be initialized again so it is invalid.

followed by the Viewcontroller code

1 @interfaceViewcontroller () <uitableviewdatasource, uitableviewdelegate>2@property (nonatomic) UITableView *TableView;3@property (nonatomic) Fetchdata *Fetchdata;4 @end5 6 @implementationViewcontroller7 8- (void) Viewdidload {9 [Super Viewdidload];TenSelf.tableview =[[UITableView alloc]initwithframe:self.view.bounds]; One [Self.tableview setdelegate:self]; A [Self.tableview setdatasource:self]; - [Self.view AddSubview:self.tableView]; -Self.fetchdata =[[Fetchdata alloc]init]; the [Self.fetchdata Fetchdata]; -      -[[Nsnotificationcenter defaultcenter]addobserver:self selector: @selector (Reload) name:@"Reload" Object: nil]; - } +  -- (void) reload{ + [Self.tableview Reloaddata]; A[[Nsnotificationcenter defaultcenter]removeobserver:self Name:@"Reload" Object: nil]; at } -  --(Nsinteger) Numberofsectionsintableview: (UITableView *) TableView - { -     return 1; - } in  --(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) section to { +     returnSelf.fetchData.resultArray.count; - } the  *-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath $ {Panax NotoginsengUITableViewCell *cell = [TableView dequeuereusablecellwithidentifier:@"Cell"]; -     if(!cell) { thecell = [[UITableViewCell alloc]initwithstyle:uitableviewcellstyledefault Reuseidentifier:@"Cell"]; +     } ACell.textLabel.text =[Self.fetchData.resultArray ObjectAtIndex:indexPath.row]; the     returncell; +}

Note the reload method of 17 rows, and 20 rows, after calling the Fetchdata method, emits an observer, when the notification of the post is observed, calls the Reload method, refreshes TableView, and implements asynchronous processing

Here is a nsurlsession version in the Viewcontroller implementation of the method, and afnetworking similar

1- (void) Viewdidload {2 [Super Viewdidload];3Self.tableview =[[UITableView alloc]initwithframe:self.view.bounds];4 [Self.tableview setdelegate:self];5 [Self.tableview setdatasource:self];6 [Self.view AddSubview:self.tableView];7 [self fetchsessiondata];8 }9 Ten- (void) Fetchsessiondata One { ASelf.resultarraylocal =[[Nsmutablearray alloc]init]; -Nsurlsession *session =[Nsurlsession sharedsession]; -Nsurl *url = [Nsurl urlwithstring:@"Https://itunes.apple.com/us/rss/topsongs/limit=10/json"]; theNsurlsessiondatatask *datatask = [Session Datataskwithurl:url completionhandler:^ (NSData * _nullable data, Nsurlresponse * _nullable response, Nserror *_nullable Error) { -Nsdictionary *json = [nsjsonserialization jsonobjectwithdata:data options:0Error:nil]; -Nsdictionary *feed = [JSON objectforkey:@"Feed"]; -Nsarray *entry = [Feed Objectforkey:@"entry"]; +          for(Nsdictionary *detaildictinchentry) { -             //[self.resultarraylocal addobject:[detaildict valueforkeypath:@ "Title.label"]; +Nsdictionary *title = [detaildict objectforkey:@"title"]; ANSString *str = [title Objectforkey:@"label"]; at [self.resultarraylocal addobject:str]; -              -         } -          - [Self.tableview Reloaddata]; -     }]; in [Datatask resume]; - } to  +-(Nsinteger) Numberofsectionsintableview: (UITableView *) TableView - { the     return 1; * } $ Panax Notoginseng-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) section - { the     returnSelf.fetchData.resultArray.count; + } A  the-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath + { -UITableViewCell *cell = [TableView dequeuereusablecellwithidentifier:@"Cell"]; $     if(!cell) { $cell = [[UITableViewCell alloc]initwithstyle:uitableviewcellstyledefault Reuseidentifier:@"Cell"]; -     } -Cell.textLabel.text =[Self.fetchData.resultArray ObjectAtIndex:indexPath.row]; the     returncell; -}

The main focus is to mention the usage of [nsnotificationcenter] under MVC, so that asynchronous flush implementation

Welcome to my homepage: http://www.jiachengzhi.com

iOS Development-afnetworking/nsurlsession Asynchronous processing

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.