Ytknetwork Basic Guide Ytknetwork and Usage

Source: Internet
Author: User

Ytknetwork Basic guide:ytknetwork Basic Guidance

In the article, we'll introduce the basic usage of Ytknetwork. in this article, we will describe the basic usage of Ytknetwork.

Ytknetwork ' s basic compositionthe basic composition of ytknetwork

Ytknetwork mainly contains the following classes: Ytknetwork mainly includes the following courses:

    • Ytknetworkconfig:it ' s used for setting global network host address and CDN Address. Ytknetworkconfig: used to set the global network host address and CDN Address.
    • Ytkrequest:it ' s The parent of all the detailed network request Classes. All network request classes should inherit it.  Every subclass of YTKRequest represents a specific network Request. Ytkrequest: All detailed network requests for the parent class. All network requests should inherit its class. Each subclass of Ytkrequest represents a specific network Request.

We'll explain the above 2 classes ' detailed usage below. we will explain the following 2 types of detailed usage .

Ytknetworkconfig classYtknetworkconfig class

The Ytknetworkconfig class has 2 usages: the Ytknetworkconfig class has two uses:

    1. Set Global Network host address and CDN Address. Establish a global network host address and CDN Address.
    2. Manage the filters which implemented YTKUrlFilterProtocol protocol (we'll discuss it in pro usage guide). the managed filter implements the Ytkurlfilterprotocol protocol (we will discuss it in the professional usage guide).

We use the Ytknetworkconfig to set global network host address because:

We use Ytknetworkconfig to set the global network host address because:

    1. According to the Do Not Repeat Yourself Principle,we should write the host address is only once. according to the principle of not repeating itself, we should only write once the host Address.
    2. In practise, we testers need to switch host addresses at Runtime. Ytknetworkconfig can satisfy such requirement. in practice, Our testers need to switch the host address at run Time. The ytknetworkconfig can meet such requirements.

We should set Ytknetworkconfig ' s property at the beggining app launching, the sample is Below:

我们应该设置YTKNetworkConfig的属性在应用程序启动的发出召唤,下面的示例:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ YTKNetworkConfig *config = [YTKNetworkConfig sharedInstance]; config.baseUrl = @"http://yuantiku.com"; config.cdnUrl = @"http://fen.bi";}

After setting, the all network requests would use Ytknetworkconfig's property as baseUrl their host addresses, and they would use The property of cdnUrl Ytknetworkconfig as their CDN addresses.

After setting up all network requests will use Ytknetworkconfig BaseURL real estate as their host address, they will use Cdnurl property Ytknetworkconfig CDN Address.

If we want to switch server address, we can just the change Ytknetworkconfig ' s property baseUrl .

If we want to switch the server address, we can change the ytknetworkconfig baseurl Property.

Ytkrequest classYtkrequest class

The design idea of Ytknetwork is, every specific network request should be a object. So after using the ytknetwork, all your request classes should inherit Ytknetwork. Through overwriting the methods of super class, you can build your own specific and distinguished Request. The key idea behind this is somewhat like the Command Pattern.

Ytknetwork's design philosophy is that every particular network request should be an Object. So after using ytknetwork, all your requirements should inherit the Ytknetwork class. By overriding the methods of the parent class, you can build your own specific and outstanding requests. The key idea behind this is a bit like command Mode.

For example, if we want to send a POST request http://www.yuantiku.com/iphone/register to, with username and password as arguments, then the class should be As Following:

for example, if we want to send a POST request to http://www.yuantiku.com/iphone/register, username and password as parameters, Then the class should look like This:

  //registerapi.h#import "YTKRequest.h" @interface registerapi: Ytkrequest-(id) initwithusername: (nsstring *) username password: (nsstring *) password; @end  //registerapi.m#import "RegisterApi.h" @implementation registerapi {nsstring *_    Username NSString *_password;}    -(id) initwithusername: (nsstring *) username password: (nsstring *) password {self = [super init];        If (self) {_username = username;    _password = password; }   return self;} -(nsstring *) Requesturl {//"http://www.yuantiku.com" is a set in ytknetworkconfig, so we ignore it return @ "/iphone /register ";} -(YTKREQUESTMETHOD) Requestmethod {return ytkrequestmethodpost;} -(id) requestargument {return @{@ "username": _username, @ "password": _password};} @end    

In above Example: on the example above:

  • Through overwriting requestUrl method, we ' ve indicated the detailed Url. Bacause host address has been set YTKNetworkConfig in, we should not write the host address in requestUrl Method.
  • By overriding the Requesturl method, we represent the detailed url. Because at the Ytknetworkconfig host address, we should not write the Requesturl host address Method.
  • Through overwriting requestMethod method, we ' ve indicated the use of the POST method.
  • By overriding the Requestmethod method, we use the post Method.
  • Through overwriting requestArgument method, we ' ve provided the POST Data. If arguments username password and contain any charaters which should be escaped, the library would do it automatically.
  • By overwriting the requestargument method, we provide the post Data. If the user name and password parameters contain any features that should escape, the library will Automatically.
call Registerapi called Registerapi

OK, How can we use the RegisterApi ? We can call it in the login view Controller. After initializing the instance, we can call their start or startWithCompletionBlockWithSuccess method to send the request to the network request Queue.

ok, How do we use registerapi? we can call it login view Controller. After you initialize the instance, you can call its startup or Startwithcompletionblockwithsuccess method to send the request to the network request Queue.

Then we can get the network response by block or delegate Mechanism.

Then we can block or delegate the network response Mechanism.

- (void)loginButtonPressed:(id)sender {    NSString *username = self.UserNameTextField.text;    NSString *password = self.PasswordTextField.text;    if (username.length > 0 && password.length > 0) {        RegisterApi *api = [[RegisterApi alloc] initWithUsername:username password:password];        [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {            // you can use self here, retain cycle won‘t happen            NSLog(@"succeed");        } failure:^(YTKBaseRequest *request) {            // you can use self here, retain cycle won‘t happen            NSLog(@"failed");        }];    }}

Kindly be noted this can use directly in the self block where the retain cycle won ' t Happen. Because Ytkrequest would set callback block to nil, so the block would be a released right after the network request completed .

Note that you can use the block retention cycle of the direct ego that does not occur. Because Ytkrequest has a callback block of zero, The block publishes the network request when it is Completed.

Besides block the callback, Ytkrequest also support delegate callback Method. The example is Below:

In addition to block callbacks, Ytkrequest also supports delegate callback METHODS. The following examples Are:

- (void)loginButtonPressed:(id)sender {    NSString *username = self.UserNameTextField.text;    NSString *password = self.PasswordTextField.text;    if (username.length > 0 && password.length > 0) {        RegisterApi *api = [[RegisterApi alloc] initWithUsername:username password:password];        api.delegate = self;        [api start];    }}- (void)requestFinished:(YTKBaseRequest *)request {    NSLog(@"succeed");}- (void)requestFailed:(YTKBaseRequest *)request {    NSLog(@"failed");}
Verify Response JSONValidate response JSON

The response JSON from the server cannnot is always Trusted. Client may crash if the data are returned in faulty format from the Server.

The response JSON from the server is not always trustworthy. The customer may crash if the data returns an incorrect format from the Server.

Ytkrequest provides a simple-to-verity the Respose JSON.

Ytkrequest Authenticity Respose JSON provides an easy way to do This.

For example, let's say we need to send a GET request to http://www.yuantiku.com/iphone/users address with a argument named userId . The server would return the target user ' s information, including nickname and Level. We shall guarantee the response type of nickname is a string and the type of level is Number. To ensure this, we can overwrite the as jsonValidator following:

For example, Suppose we need to send a GET request to the Http://www.yuantiku.com/iphone/users address and a name UserID Parameter. The server returns information for the target user, including nicknames and Levels. We will guarantee that the Nickname's response type is the type of string and level Number. To ensure this, we can overwrite Jsonvalidator as Follows:

- (id)jsonValidator {    return @{        @"nick": [NSString class],        @"level": [NSNumber class]    };}

The whole code sample is Below: The entire example is as Follows:

// GetUserInfoApi.h#import "YTKRequest.h"@interface GetUserInfoApi : YTKRequest- (id)initWithUserId:(NSString *)userId;@end// GetUserInfoApi.m#import "GetUserInfoApi.h"@implementation GetUserInfoApi {    NSString *_userId;}- (id)initWithUserId:(NSString *)userId {    self = [super init];    if (self) {        _userId = userId;    }    return self;}- (NSString *)requestUrl {    return @"/iphone/users";}- (id)requestArgument {    return @{ @"id": _userId };}- (id)jsonValidator {    return @{        @"nick": [NSString class],        @"level": [NSNumber class]    };}@end

Here is some others samples: here are some other samples:

    • Require return string array: need to return arrays of strings:
- (id)jsonValidator {    return @[ [NSString class] ];}
    • Here are one complex sample from US company: This is a complex sample from our companies :
- (id)jsonValidator {    return @[@{        @"id": [NSNumber class],        @"imageId": [NSString class],        @"time": [NSNumber class],        @"status": [NSNumber class],        @"question": @{            @"id": [NSNumber class],            @"content": [NSString class],            @"contentType": [NSNumber class]        }    
Use CDN address using CDN addresses

If you need to use CDN address in some of your requests, just overwrite the - (BOOL)useCDN; method, and return in the YES method.

If you need to use a CDN address on your request, just overwrite-(BOOL) usecdn; method, and return to the Yesin method.

For example, if we had a interface for image downloading, and the address was with the host as the http://fen.bi/image/imageId http://fen.bi CDN address . Then the code should is Below:

For example, If we have an interface picture download, the address is Http://fen. Bi/image/imageid with host Http://fen. Bi as the CDN address. The following code should then be:

// GetImageApi.h#import "YTKRequest.h"@interface GetImageApi : YTKRequest- (id)initWithImageId:(NSString *)imageId;@end// GetImageApi.m#import "GetImageApi.h"@implementation GetImageApi {    NSString *_imageId;}- (id)initWithImageId:(NSString *)imageId {    self = [super init];    if (self) {        _imageId = imageId;    }    return self;}- (NSString *)requestUrl {    return [NSString stringWithFormat:@"/iphone/images/%@", _imageId];}- (BOOL)useCDN {    return YES;}@end
Resumable downloadingRecoverable Downloads

If you want to enable resumable downloading, you just need to overwrite the resumableDownloadPath method and provide a temporary path to Save the half-downloaded Data.

If you want to make a recoverable download, you only need to overwrite the Resumabledownloadpath method and provide a temporary path to save half-downloaded Data.

We can modify above example to support Resumable Downloading.

We can modify the example above to support a recoverable download.

@implementation GetImageApi {    NSString *_imageId;}- (id)initWithImageId:(NSString *)imageId {    self = [super init];    if (self) {        _imageId = imageId;    }    return self;}- (NSString *)requestUrl {    return [NSString stringWithFormat:@"/iphone/images/%@", _imageId];}- (BOOL)useCDN {    return YES;}- (NSString *)resumableDownloadPath {    NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];    NSString *cachePath = [libPath stringByAppendingPathComponent:@"Caches"];    NSString *filePath = [cachePath stringByAppendingPathComponent:_imageId];    return filePath;}@end
Cache response Data Caching response

We ' ve implemented GetUserInfoApi the before, which is used for getting user Information.

We have implemented the GETUSERINFOAPI before to get the user Information.

We may want to cache the Response. In the following example, we overwrite cacheTimeInSeconds the method and then our API would automatically cache data for specified amount O F Time. If the cached data is not expired, the API S and start would startWithCompletionBlockWithSuccess return cached data as a result directly.

We may want to cache the Response. In the following example, we overwrite the Cachetimeinseconds method, and our API automatically caches the data for the specified Time. If the cached data does not expire, the start and startwithcompletionblockwithsuccess of the API will return the cached data results directly.

@implementation GetUserInfoApi {    NSString *_userId;}- (id)initWithUserId:(NSString *)userId {    self = [super init];    if (self) {        _userId = userId;    }    return self;}- (NSString *)requestUrl {    return @"/iphone/users";}- (id)requestArgument {    return @{ @"id": _userId };}- (id)jsonValidator {    return @{        @"nick": [NSString class],        @"level": [NSNumber class]    };}- (NSInteger)cacheTimeInSeconds {    // cache 3 minutes, which is 60 * 3 = 180 seconds    return 60 * 3;}@end

The cache mechanism is transparent to the controller, which means the request caller could get the result right after Invoki ng the request without casuing any real network traffic as a long as its cached data remains valid.

The caching mechanism is transparent to the controller, which means that the requesting caller may invoke the requested result after not because of any real network traffic, as long as its cached data is still VALID.

The above code samples is available in the Ytknetworkdemo Project.

The code sample above is available in the Ytknetworkdemo Project.

Ytknetwork Basic Guide Ytknetwork and Usage

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.