IOS 8: "Go" using afnetworking, Sdwebimage and Ohhttpstubs

Source: Internet
Author: User
Tags root access

Source Address: http://blog.shiqichan.com/using-afnetworking-sdwebimage-and-ohhttpstubs/

Wrote an example on GitHub.

This is the animation that runs:

The following are the main topics:

    • Afnetworking-based HTTP operations, get get Web pages and JSON data, upload files, download files, and load images
    • Loading pictures based on Sdwebimage
    • Ohhttpstubs-based fake network response for testing (stub), and can simulate the delay of the network
Using the Nsurlsession-based afnetworking API

Afnetworking has 2 sets of APIs for network operations:

    • Based on Nsurlconnection
    • Based on Nsurlsession

The latter is the new API for iOS 7/mac OS X 10.9 and later.

This article is well written: from Nsurlconnection to nsurlsession, it shows what the latter has done to improve and strengthen.

Now a growing number of iOS projects require iOS 7 minimum, so that we can start experimenting with this new way.

Get request to get normal page text

Afhttpsessionmanager is an API that uses Nsurlsession.

12345678910111213141516171819 Nsurl *baseurl = [nsurl urlwithstring:@ "http://localhost/"]; //Set up and add header informationNsurlsessionconfiguration *config = [Nsurlsessionconfiguration defaultsessionconfiguration]; [Config sethttpadditionalheaders:@{@ "user-agent": @ "My Browser"}]; Afhttpsessionmanager *manager=[[afhttpsessionmanager alloc] Initwithbaseurl:baseurl sessionconfiguration:config]; Manager. Responseserializer = [Afhttpresponseserializer serializer];Manager. Responseserializer. acceptablecontenttypes = [nsset setwithobject:@ "text/html"]; //Set parameters for GET requestnsdictionary *params=[[nsdictionary alloc] Initwithobjectsandkeys:@ "3",@ "id",nil]; //Initiate a GET request[Manager GET:@ "" Parameters:params success:^ (Nsurlsessiondatatask *task, ID responseobject) { NSLog (@ "HTML:%@", [[nsstring Alloc]initwithdata:responseobject encoding:nsutf8stringencoding]); } failure:^ (Nsurlsessiondatatask *task,nserror *error) {NSLog (@ "Visit error:%@", error); }];

To facilitate testing, this example writes a simple Web server,httpserver.js.

To run httpserver.js, you need to install the node. JS Environment. And then:

sudo node httpServer

I use port 80, which requires root access in a Mac environment.

Get request, get JSON data

Method and Get Request Web page text is similar, individual parameters or set objects have different:

12345678910111213 Nsurl *baseurl = [nsurl urlwithstring:@ "http://localhost/"]; Nsurlsessionconfiguration *config = [Nsurlsessionconfiguration defaultsessionconfiguration]; [Config sethttpadditionalheaders:@{@ "user-agent": @ "My Browser"}]; Afhttpsessionmanager *manager=[[afhttpsessionmanager alloc] Initwithbaseurl:baseurl sessionconfiguration:config];nsdictionary *params=[[nsdictionary alloc] Initwithobjectsandkeys:@ "8",@ "id",nil]; [Manager GET:@ "/json" Parameters:params success:^ (Nsurlsessiondatatask *task, ID responseobject) { nsdictionary * object= (nsdictionary *) responseobject; NSLog (@ "Response message:%@", object[@ "message"]); } failure:^ (Nsurlsessiondatatask *task,nserror *error) {NSLog (@ "Visit error:%@", error); }];
Download file

The Afnetworking API returns NSURLSessionDownloadTask and can be used for cancellation, pause, and recovery of network requests.

In fact, the Get method above also returns this object, but the download file time may be longer, there may be a need for this.

1234567891011121314 Nsurlsessionconfiguration *configuration = [Nsurlsessionconfiguration defaultsessionconfiguration]; Afurlsessionmanager *manager = [[Afurlsessionmanager alloc] initwithsessionconfiguration:configuration];Nsurl *url = [nsurl urlwithstring:@ "Http://www.baidu.com/img/bdlogo.png"]; nsurlrequest *request = [nsurlrequest requestwithurl:url]; Nsurlsessiondownloadtask *downloadtask = [Manager downloadtaskwithrequest:request Progress:Nil destination:^Nsurl * (nsurl *targetpath, Nsurlresponse *response) { Nsurl *documentsdirectoryurl = [[nsfilemanager Defaultmanager] urlfordirectory:nsdocumentdirectory inDomain: Nsuserdomainmask Appropriateforurl:nil Create:NO error:nil]; return [Documentsdirectoryurl urlbyappendingpathcomponent:[response Suggestedfilename]];} completionhandler:^ (Nsurlresponse *response,nsurl *filepath, nserror *error) { NSLog (@ "File downloaded to:%@", FilePath); Uploadfilepath=filepath;}]; [Downloadtask resume];
Loading pictures with afnetworking

Need to introduce:

1 #import <UIImageView+AFNetworking.h>

Then, Uiimageview will have setimagewithurl for use.

12 Nsurl *url = [nsurl urlwithstring:@ "Http://www.baidu.com/img/bdlogo.png"]; [ImageView Setimagewithurl:url];

In addition, there are other ways to set up placeholder images, image download success and failure processing, and how to stop a picture download.

1234 – Setimagewithurl:– setimagewithurl:p laceholderimage:– setimagewithurlrequest: Placeholderimage:Success: failure:– cancelimagerequestoperation
Loading pictures with Sdwebimage

Sdwebimage, the call way and afnetworking similar, the function is more powerful, the use is also very popular.

Need to introduce:

1 #import <SDWebImage/UIImageView+WebCache.h>

Code:

12 Nsurl *url = [nsurl urlwithstring:@ "Http://www.sogou.com/images/logo/new/sogou.png"]; [ImageView Sd_setimagewithurl:url];

The following is a complete list of methods:

123456789101112 –Sd_imageurl–Sd_setimagewithurl:–sd_setimagewithurl:p laceholderimage: –sd_setimagewithurl:p laceholderimage: Options: –sd_setimagewithurl: Completed: –sd_setimagewithurl:p laceholderimage: Completed: –sd_setimagewithurl:p laceholderimage: Options: Completed: –sd_setimagewithurl:p laceholderimage: Options:p rogress: Completed: –sd_setimagewithpreviouscachedimagewithurl: andplaceholderimage: Options:p rogress: Completed: –Sd_setanimationimageswithurls:–Sd_cancelcurrentimageload–Sd_cancelcurrentanimationimagesload

More options than the afnetworking option, such as the ability to set SDWebImageOptions :

12345678910 typedef ns_options (Nsuinteger, sdwebimageoptions) {sdwebimageretryfailed = 1 < < 0, sdwebimagelowpriority = 1 < < 1, sdwebimagecachememoryonly = 1 < < 2, sdwebimageprogressivedownload = 1 < < 3, sdwebimagerefreshcached = 1 < < 4, Sdwebimagecontinueinbackground = 1 < < 5, sdwebimagehandlecookies = 1 < < 6, sdwebimageallowinvalidsslcertificates = 1 < < 7, };

ALSO: typedef void (^sdwebimagedownloaderprogressblock) (Nsinteger receivedsize, Nsinteger expectedsize)

    • You can create animations with a set of pictures: Sd_setanimationimageswithurls
    • Display pictures first using the previous cache? Sd_setimagewithpreviouscachedimagewithurl, which I understood from the literal sense, had not yet used
    • There is a process block, sd_setImageWithURL:placeholderImage:options:progress:completed: which can be obtained receivedSize and expectedSize byte parameters, used to display the process percentage

In addition, IOS image caching. Libraries Benchmark (sdwebimage vs Fastimagecache), this article tests and contrasts, and the conclusion is sdwebimage better.

Afnetworking Uploading Files
12345678910111213141516 Nsmutableurlrequest *request = [[Afhttprequestserializer serializer] Multipartformrequestwithmethod:@ "POST" urlstring:@ "http://localhost/upload" parameters:nil constructingbodywithblock:^ (id< Afmultipartformdata> formData) { [FormData Appendpartwithfileurl:uploadfilepath Name:@ "File" FileName:@ "filename.jpg" MimeType:@ "Image/jpeg" error:nil]; } Error:Nil];Afurlsessionmanager *manager = [[Afurlsessionmanager alloc] Initwithsessionconfiguration:[nsurlsessionconfiguration Defaultsessionconfiguration]]; Nsprogress *progress =Nil;Nsurlsessionuploadtask *uploadtask = [Manager uploadtaskwithstreamedrequest:request progress:&progress completionhandler:^ (Nsurlresponse *response,ID responseobject, nserror *error) { if (error) {NSLog (@ "error:%@", error); }else {NSLog (@ "%@%@", response, Responseobject); }}]; [Uploadtask resume];

You can NSProgress do this by getting the upload progress (how do I do it?) )

Using Ohhttpstubs to forge HTTP responses

Ohhttpstubs, which can be used to forge HTTP responses so that the iOS developer can test the network service without relying on the server side.

This API, while supporting:

    • Nsurlconnection
    • Nsurlsession

However, there is a problem to note, if the app to AppStore, it is not connected to ohhttpstubs.

The following is how to use, first look at the code:

123456789101112131415 nsstring *baseurl=@ "http://localhost"; //mock for Http://locahost/json request[Ohhttpstubs stubrequestspassingtest:^BOOL (nsurlrequest *request) { nsdictionary *params=[nsdictionary objectsfromurlquerystring:request. URL. query]; NSLog (@ "ID:%@", params[@ "id"]); return [Request. URL absolutestring] rangeofstring:[nsstring stringWithFormat:@ "%@/json", BaseUrl]]. location==0; } withstubresponse:^ohhttpstubsresponse* (nsurlrequest *request) {NSLog (@ "Reqeust:%@", request); nsstring* fixture = Ohpathforfileinbundle (@ "Test.json",nil); return [[Ohhttpstubsresponse responsewithfileatpath:fixtureStatusCode:headers:@{@ "Content-type":@ "Text/json"} ]requesttime:0 ResponseTime:0]; }];

The basic idea is to invoke a method that implements the response of a specified HTTP request by 2 callbacks (blocks) to forge:

    • is the request to intercept
    • After interception, create a response

The above code also demonstrates:

    • How to extract the parameters of a GET request from a URL is used here: Urlquerytococoa
    • Use local files as JSON data to add to the HTTP response
    • can set the delay of request and response, requestTime:0 responseTime:0 this is quite useful

can also be used to forge a picture of the response, tested, the above afnetworking and Sdwebimage are valid.

12345678910 //get image with Sdwebimage[Ohhttpstubs stubrequestspassingtest:^BOOL (nsurlrequest *request) { return [Request. URL absolutestring] isequaltostring:@ "Http://www.sogou.com/images/logo/new/sogou.png"]; } withstubresponse:^ohhttpstubsresponse* (nsurlrequest *request) {NSLog (@ "Reqeust:%@", request); nsstring* fixture = Ohpathforfileinbundle (@ "Taobao.png",nil); return [[Ohhttpstubsresponse responsewithfileatpath:fixtureStatusCode:headers:@{@ "Content-type":@ "Image/png"} ]requesttime:0 ResponseTime:0]; }];

When testing, be aware that it may have been obtained from a real network, so there will be a cache. You need to remove the app and reinstall the test.

You should see an effect similar to the following (using a local picture):

Ohhttpstubs these code, just in the app boot load once, can be written in AppDelegate :

123 - (BOOL) Application:(uiapplication *) application didfinishlaunchingwithoptions:( Nsdictionary *) launchoptions {[[Afnetworkreachabilitymanager Sharedmanager] Startmonitoring]; [Httpmock Initmock];

The code is screened out and the real network is used naturally.

When compiling the formal use of code, you can consider conditional compilation.

Afnetworking's Network Monitoring API

Provided AFNetworkReachabilityManager can be used alone, very convenient for monitoring network changes.

For example, you can start the monitor by performing the following actions after the app starts:

12 - (BOOL) Application:(uiapplication *) application didfinishlaunchingwithoptions:( Nsdictionary *) launchoptions {[[Afnetworkreachabilitymanager Sharedmanager] Startmonitoring];

In the Viewcontroller:

123456 -(void) Viewdidload {[[Afnetworkreachabilitymanager Sharedmanager] Setreachabilitystatuschangeblock: ^ ( Afnetworkreachabilitystatus status) {NSLog (@"reachability:%@", Afstringfromnetworkreachabilitystatus (status));}];}

Monitor network changes, and make appropriate actions, such as pop-up prompt box.

When used formally:

    • can be considered in appdelegate setReachabilityStatusChangeBlock , when the state changes, by NSNotification issuing a notification
    • viewDidAppear viewWillDisappear Monitoring and canceling monitoring notifications in and out of individual Viewcontroller

This is a vision, not yet implemented, and perhaps problematic.

But at least should not be used in Viewcontroller, as in this case setReachabilityStatusChangeBlock .

IOS 8: "Go" using afnetworking, Sdwebimage, and ohhttpstubs

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.