YTKNetwork Documentation

repository·master·Indexed 27 days ago

https://github.com/kanyun-inc/ytknetwork

A high-level iOS network request utility built on top of AFNetworking. It utilizes the Command Pattern via YTKRequest to decouple network logic from controllers. Key features include request chaining (YTKChainRequest), batching (YTKBatchRequest), version-based and time-based caching, JSON response validation, and resumable downloads. It provides centralized URL management through YTKNetworkConfig for base and CDN URLs, and supports both block and delegate callback patterns.

Tokens
4.9K
Snippets
17
Records
28
Agent score
90%

What's inside YTKNetwork

  1. Overview of YTKNetwork features

    master

    YTKNetwork is a high-level request utility based on AFNetworking designed for complex projects. Key features include:

    • Caching: Response caching by expiration time or version number.
    • URL Management: Set common base URLs and CDN URLs; support for URL filtering, partial URL replacement, or appending common parameters.
    • Request Management: Batch requests (YTKBatchRequest), chained requests (YTKChainRequest), and resumeable downloads.
    • Validation: Built-in JSON response validation.
    • Extensibility: A plugin mechanism to handle request start and finish (e.g., a plugin for showing a 'Loading' HUD is provided).
    • Callbacks: Supports both block and delegate callback patterns.
  2. Core concepts of YTKNetwork

    master

    YTKNetwork is a high-level networking library for iOS built on top of AFNetworking. It uses the Command pattern by encapsulating every network request into an object.

    To use YTKNetwork, you must create a custom request class by inheriting from YTKRequest and overriding its methods to define the specific request behavior. This approach provides several benefits:

    • Isolation: Decouples your network requests from the underlying third-party library (e.g., AFNetworking), making it easier to swap implementations.
    • Common Logic: Allows handling common logic (like data versioning, caching, or authentication) in a base class.
    • Persistence: Facilitates the persistence of request objects.

    Key Features:

    • Time-based and version-based request caching.
    • Unified configuration for Server and CDN addresses.
    • JSON validity checking.
    • File breakpoint resumption (resumable downloads).
    • Support for both block and delegate callback modes.
    • Batch request execution via YTKBatchRequest.
    • Chained/dependent request execution via YTKChainRequest.
    • URL filtering for adding parameters or modifying paths.
    • Plugin mechanism for extending functionality (e.g., showing a loading HUD).
  3. Use NSURLSessionDownloadTask for download requests

    master

    Download requests in 2.0 use NSURLSessionDownloadTask. If you set the resumableDownloadPath property of a YTKRequest to a non-nil value, the file will be automatically saved to that path upon completion.

    Download Request Properties:

    • responseData: Not available.
    • responseString: Not available.
    • responseObject: Returns an NSURL representing the local file path.

    Progress Tracking: Progress is now handled via AFURLSessionTaskProgressBlock, which provides an NSProgress object. Use totalUnitCount and completedUnitCount to track progress.

  4. Create a custom network request by subclassing YTKRequest

    master

    YTKNetwork uses the Command pattern where every network request is encapsulated in an object. To create a new request, subclass YTKRequest and override the following methods:

    • requestUrl: Return the path relative to the baseUrl (do not include the domain).
    • requestMethod: Return the HTTP method (e.g., YTKRequestMethodPOST).
    • requestArgument: Return a dictionary containing the request parameters. Special characters like Chinese or spaces are automatically encoded.

    Example of a POST request for registration:

    // 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 {
        return @"/iphone/register";
    }
    
    - (YTKRequestMethod)requestMethod {
        return YTKRequestMethodPOST;
    }
    
    - (id)requestArgument {
        return @{
            @"username": _username,
            @"password": _password
        };
    }
    @end
  5. Handle URL concatenation changes

    master

    In 2.0, baseUrl and requestUrl are concatenated using [NSURL URLWithString:relativeToURL].

    Important: If your requestUrl starts with a / and your baseUrl contains a path (other than the Host), the requestUrl will be appended to the root of the host, potentially stripping the baseUrl path. To avoid this, ensure requestUrl does not have a leading / if your baseUrl includes a path component.

  6. Migrate YTKRequest properties from 1.X to 2.X

    master

    YTKNetwork 2.0 has replaced AFHTTPRequestOperation with NSURLSessionTask. When migrating from 1.X, update your property access as follows:

    1.X Property2.X Property
    requestOperationrequestTask
    requestOperationErrorerror
    requestOperation.responseresponse
    requestOperation.requestcurrentRequest & originalRequest

    Note: currentRequest and originalRequest will return nil unless they are accessed after the request has called start.

    // YTKNetwork 1.X
    @property (nonatomic, strong) AFHTTPRequestOperation *requestOperation;
    @property (nonatomic, strong, readonly, nullable) NSError *requestOperationError;
    
    // YTKNetwork 2.X
    @property (nonatomic, strong, readonly) NSURLSessionTask *requestTask;
    @property (nonatomic, strong, readonly, nullable) NSError *error;
  7. Configure YTKNetworkConfig for base URLs and CDN

    master

    Use the YTKNetworkConfig class to centrally manage the server's base URL and CDN URL. This ensures the Do Not Repeat Yourself principle and allows for easy switching between environments (e.g., testing vs. production). Set these values during application startup, typically in didFinishLaunchingWithOptions.

    • baseUrl: The primary server address used for all network requests by default.
    • cdnUrl: The address used for static resources like images, JS, or CSS.
    - (BOOL)application:(UIApplication *)application 
       didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
       YTKNetworkConfig *config = [YTKNetworkConfig sharedConfig];
       config.baseUrl = @"http://yuantiku.com";
       config.cdnUrl = @"http://fen.bi";
    }
  8. Define custom requests using YTKRequest

    master
    YTKNetwork uses the Command Pattern for handling network requests. Instead of calling network methods directly in your controllers, you should inherit from YTKRequest and override its methods to define custom request logic. This decouples your code from the underlying network framework and allows for easier persistence and common logic handling in a base class.
  9. Install YTKNetwork via CocoaPods or Carthage

    master

    You can install YTKNetwork using either CocoaPods or Carthage.

    For CocoaPods, add the following to your Podfile:

    pod 'YTKNetwork'

    For Carthage, add the following to your Cartfile:

    gitub "yuantiku/YTKNetwork" ~> 3.0
    pod 'YTKNetwork'
  10. Configure global network and CDN addresses with YTKNetworkConfig

    master

    Use the YTKNetworkConfig class to set the global baseUrl and cdnUrl. This should be done during application launch (e.g., in didFinishLaunchingWithOptions). Once set, all YTKRequest subclasses will automatically use these addresses as their host and CDN prefixes.

    - (BOOL)application:(UIApplication *)application 
       didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
       YTKNetworkConfig *config = [YTKNetworkConfig sharedConfig];
       config.baseUrl = @"http://yuantiku.com";
       config.cdnUrl = @"http://fen.bi";
    }
  11. Execute a YTKRequest using blocks or delegates

    master

    After initializing your YTKRequest subclass, you can trigger the request using one of two mechanisms:

    Using Completion Blocks

    Use startWithCompletionBlockWithSuccess:failure: to handle results. You can safely use self inside these blocks because YTKRequest sets the callback blocks to nil upon completion, preventing retain cycles.

    Using Delegates

    Set the delegate property of your request object to an object implementing the required delegate methods, then call start.

    Example using blocks:

    RegisterApi *api = [[RegisterApi alloc] initWithUsername:username password:password];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSLog(@"succeed");
    } failure:^(YTKBaseRequest *request) {
        NSLog(@"failed");
    }];