Encapsulating Network Requests

Source: Internet
Author: User

Encapsulation network request class is convenient, suitable for many places to use.

First package Download method

If you use Cocoapods or direct reference to a third party afnetworking

Defines a class Networkingmanager, inherited from NSObject

A: write method declaration in. h

#import <Foundation/Foundation.h>

@interface Networkmanager:nsobject

-(void) Downloadwithurl: (NSString *) URL progress: (void (^) (float progress)) Progressblock Complete: (void (^) (NSString * FilePath)) Completeblock;

There are two blocks block callback methods, the first callback download progress, the second callback after the download is complete, return the file path name

@end

B: in. m Write method implementation

#import "NetWorkManager.h"

#import "Nsstring+security.h"

#import <AFNetworking/AFNetworking.h>

@implementation NetWorkManager

-(void) Downloadwithurl: (NSString *) URL progress: (void (^) (float)) Progressblock Complete: (void (^) (NSString *)) completeblock{

Under the cache file, create the folder where the MP3 file is stored

Create Folder path

NSString *mp3path = [[Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) FirstObject] stringbyappendingpathcomponent:@ "DownLoad"];

NSLog (@ "%@", Mp3path);

Nsfilemanager *filemanager = [Nsfilemanager Defaultmanager];

Determines whether the file path exists, does not exist, is created, does not exist, and does not create

if ([FileManager Fileexistsatpath:mp3path]) {

}else{

[FileManager Createdirectoryatpath:mp3path withintermediatedirectories:yes Attributes:nil Error:nil];

}

Encrypt the downloaded file name

NSString *filename = url.md5;

Create a File Store path

NSString *filepath = [Mp3path stringbyappendingpathcomponent:filename];

Determine if the file name exists, there is already downloaded, no longer download, and vice versa to download the file

if ([FileManager Fileexistsatpath:filepath]) {

Return

}

File download

Create Manager

Afurlsessionmanager *manager = [[Afurlsessionmanager alloc] Initwithsessionconfiguration:[nsurlsessionconfiguration Defaultsessionconfiguration]];

Post request with [Afhttprequestserializer serializer] Multipartformrequestwithmethod

Create request; Apply to get requests

Nsurlrequest *request = [nsurlrequest requestwithurl:[nsurl urlwithstring:url];

Create a download task

Nsurlsessiondownloadtask *task = [Manager downloadtaskwithrequest:request progress:^ (nsprogress * _Nonnull DownloadProgress) {

Back to download progress

Progressblock (Downloadprogress.completedunitcount/(downloadprogress.totalunitcount/1.0));

} Destination:^nsurl * _nonnull (Nsurl * _nonnull TargetPath, Nsurlresponse * _nonnull response) {

Return File Store path

return [Nsurl Fileurlwithpath:filepath];

} completionhandler:^ (Nsurlresponse * _nonnull response, Nsurl * _nullable filePath, Nserror * _nullable error) {

Download complete

Completeblock (Mp3path);

}];

[Task resume];

}

@end

Second Package Post network request

A: declaration of methods written in. h

Encapsulating Post Network requests

Parameter Request body

-(void) Networkwithurl: (NSString *) URL parameter: (Nsdictionary *) dic success: (void (^) (id obj)) successblock fail: (void (^) (Nserror *error)) Failblock;

Two callback methods, first callback operation after successful, second callback failure message

B: in. m Write method implementation

-(void) Networkwithurl: (NSString *) URL parameter: (Nsdictionary *) dic success: (void (^) (ID)) Successblock fail: (void (^) (Nserror *)) failblock{

Create Session Manager

Afurlsessionmanager *manager = [[Afurlsessionmanager alloc] Initwithsessionconfiguration:[nsurlsessionconfiguration Defaultsessionconfiguration]];

Create request, Post requests method

Nsurlrequest *request = [[Afhttprequestserializer serializer] multipartformrequestwithmethod:@ "POST" URLString:Url Parameters:dic Constructingbodywithblock:nil Error:nil];

Create a request task

Nsurlsessiondatatask *task = [Manager datataskwithrequest:request completionhandler:^ (nsurlresponse * _Nonnull Response, id _nullable responseobject, nserror * _nullable error) {

if (Error) {

Failblock (Error);

}else{

Successblock (Responseobject);

}

}];

Open Task

[Task resume];

}

Note: You need to Afnetworking in the third party.

the No. 226 line of the file is added

Field

Third Package Upload Image method

A: declaration of methods written in. h

Package Upload Image method

-(void) Networkwithurl: (nsstring *) URL Pic: (UIImage *) image parameter: (nsdictionary *) dic Successblock: (void (^) (id obj )) Success Failblock: (void (^) (nserror *error)) fail;

B: Implementation of the Write method in. m

-(void) Networkwithurl: (nsstring *) URL Pic: (UIImage *) image parameter: (nsdictionary *) dic Successblock: (void (^) (ID)) Success Failblock: (void (^) (Nserror *)) fail{

Create SessionManager

Afurlsessionmanager *manager = [[Afurlsessionmanager alloc] Initwithsessionconfiguration:[nsurlsessionconfiguration Defaultsessionconfiguration]];

Create request, POST requests

Nsurlrequest *request = [[Afhttprequestserializer serializer] multipartformrequestwithmethod:@ "POST" URLString:url Parameters:dic constructingbodywithblock:^ (id<afmultipartformdata> _nonnull formData) {

Submit picture/video/audio data here

Turn the picture into NSData first

Parameter 2: Scale

NSData *data = uiimagejpegrepresentation (image, 0.5);

Parameter 1: Data

Parameter 2: The server provides the field name, a moment inside called IconFile

Parameter 3: Feel free to fill in

Parameter 4: File type

[FormData appendpartwithfiledata:data name:@ "IconFile" filename:[nsstring stringwithformat:@ "%f.png", [[NSDate Date] TIMEINTERVALSINCE1970]] mimetype:@ "png/jpeg/jpg"];

} Error:nil];

Create a request task

Nsurlsessiondatatask *task = [Manager datataskwithrequest:request completionhandler:^ (nsurlresponse * _Nonnull Response, id _nullable responseobject, nserror * _nullable error) {

if (Error) {

Fail (error);

}else{

Success (Responseobject);

}

}];

[Task resume];

}

Note: This method is generally used in the registration, because the registration requires the user to select the avatar upload to the server, the general network request does not meet the requirements.

Encapsulating Network Requests

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.