All Projects → knightsj → Sjnetwork

knightsj / Sjnetwork

Licence: mit
SJNetwork is a high level network request tool based on AFNetworking and inspired on YTKNetwork.

Projects that are alternatives of or similar to Sjnetwork

Flickrsync
A command line tool to synchronise, upload, download, pictures between the local file system and Flickr. Image hash signature of the picture is used to uniquely identify the image.
Stars: ✭ 14 (-93.94%)
Mutual labels:  image, download, upload
Daisynet
1. - Alamofire与Cache封装 , 更容易存储请求数据. 2. - 封装Alamofire下载,使用更方便
Stars: ✭ 331 (+43.29%)
Mutual labels:  cache, network, download
React Files
A file input (dropzone) management component for React
Stars: ✭ 126 (-45.45%)
Mutual labels:  image, upload
Bbwebimage
A high performance Swift library for downloading, caching and editing web images asynchronously.
Stars: ✭ 128 (-44.59%)
Mutual labels:  cache, image
Ounotes
An Application built for students to access Notes , Question Papers , Syllabus and Resources for all Subjects of O.U (Osmania University) 📘👨‍🎓
Stars: ✭ 173 (-25.11%)
Mutual labels:  download, upload
Cash
HTTP response caching for Koa. Supports Redis, in-memory store, and more!
Stars: ✭ 122 (-47.19%)
Mutual labels:  cache, network
Releases
dahliaOS ISO releases
Stars: ✭ 125 (-45.89%)
Mutual labels:  image, download
Tiercel
简单易用、功能丰富的纯 Swift 下载框架
Stars: ✭ 2,241 (+870.13%)
Mutual labels:  network, download
Okhttps
如艺术一般优雅,像 1、2、3 一样简单,前后端通用,轻量却强大的 HTTP 客户端(同时支持 WebSocket 与 Stomp 协议)
Stars: ✭ 92 (-60.17%)
Mutual labels:  download, upload
Uploadcare Widget
Uploadcare Widget, an ultimate tool for HTML5 file upload supporting multiple file upload, drag&drop, validation by file size/file extension/MIME file type, progress bar for file uploads, image preview.
Stars: ✭ 183 (-20.78%)
Mutual labels:  image, upload
Recent Images
Do you noticed the new feature of Telegram or Instagram?! They show your latest images when you try to attach or post a picture. So I developed this library the same with lots of customization. Simple way to get all images of device based on date taken, name, id and other customization
Stars: ✭ 182 (-21.21%)
Mutual labels:  cache, image
Telegram Upload
Upload and download files from Telegram up to 2GiB using your account
Stars: ✭ 223 (-3.46%)
Mutual labels:  download, upload
Deta cache
缓存cache服务器
Stars: ✭ 106 (-54.11%)
Mutual labels:  cache, network
Medialoader
Cache video/audio while playing for any android media player
Stars: ✭ 97 (-58.01%)
Mutual labels:  cache, download
Ppnetworkhelper
AFNetworking 3.x 与YYCache封装
Stars: ✭ 1,586 (+586.58%)
Mutual labels:  cache, afnetworking
Angular File Uploader
Angular file uploader is an Angular 2/4/5/6/7/8/9/10 + file uploader module with Real-Time Progress Bar, Responsive design, Angular Universal Compatibility, localization and multiple themes which includes Drag and Drop and much more.
Stars: ✭ 92 (-60.17%)
Mutual labels:  image, upload
Fgdownloader
用于断点下载、任务队列、上传进度、下载进度
Stars: ✭ 143 (-38.1%)
Mutual labels:  download, upload
Googliser
a fast BASH multiple-image downloader
Stars: ✭ 202 (-12.55%)
Mutual labels:  image, download
Httptransfertasks
Cross Platform HTTP Transfers for downloading and uploading (supports background operations)
Stars: ✭ 87 (-62.34%)
Mutual labels:  download, upload
Ffimageloading
Image loading, caching & transforming library for Xamarin and Windows
Stars: ✭ 1,288 (+457.58%)
Mutual labels:  cache, image

SJNetwork

Introduction

SJNetwork provides a high level network request API based on AFNetworking and inspired by YTKNetwork: generating network request object according to the configuration of a specific network request(url, method, parameters etc.) and managing requests by the corresponding objects.

Document for Chinese-convenient reader:中文文档

Features

  • Ordinary request: sending GET,POST,PUT,DELETE network request.
    • write and load caches, configure cache available time duration​
  • Upload request: sending upload image(s) network request
    • one and more than one image uploading and configure compress ratio before uploading​
  • Download request: sending download file network request
    • resumable or not
    • background downloading supporting or not
  • Default parameters:default parameters will be added on request body
  • Custom header: configuring custom request header(key-value)
  • Base url configuration : server url of network requests
  • Request management:canceling one or more than one current network requests; checking current requests' information
  • Cache operation: writing, loading or clearing one or more than one cache of network requests ; calculating cache size
  • Debug mode switch: for convenience of debugging

Usage

Method1: using Cocoapods:

pod 'SJNetwork'

then

#import <SJNetwork/SJNetwork.h>

Method2: moving SJNetworkfolder into your project.

then

#import "SJNetwork.h"

Basic Configuration

Server url

[SJNetworkConfig sharedConfig].baseUrl = @"http://v.juhe.cn";

Default parameters

[SJNetworkConfig sharedConfig].defailtParameters = @{@"app_version":[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"],
                                                        @"platform":@"iOS"};

Timeout seconds

[SJNetworkConfig sharedConfig].timeoutSeconds = 30;//default is 20s

Debug mode

[SJNetworkConfig sharedConfig].debugMode = YES;//default is NO

Add request header

[[SJNetworkConfig sharedConfig] addCustomHeader:@{@"token":@"2j4jd9s74bfm9sn3"}];

or

[[SJNetworkManager sharedManager] addCustomHeader:@{@"token":@"2j4jd9s74bfm9sn3"}];

The input key-value pair will be added in network request header.

If a pair with same key-value dose not exist, then add it, if it exists, then replace it.

Ordinary Network Request

POST request (none writing or none loading cache):

[[SJNetworkManager sharedManager] sendPostRequest:@"toutiao/index"
                                       parameters:@{@"type":@"top",
                                                    @"key" :@"0c60"}
  
     success:^(id responseObject) {

  } failure:^(NSURLSessionTask *task, NSError *error, NSInteger statusCode) {

  }];

POST request ( writing and loading cache):

[[SJNetworkManager sharedManager] sendPostRequest:@"toutiao/index"
                                       parameters:@{@"type":@"top",
                                                    @"key" :@"0c60"}
                                        loadCache:YES
                                    cacheDuration:180
  success:^(id responseObject) {

} failure:^(NSURLSessionTask *task, NSError *error, NSInteger statusCode) {

}];

If loadcache is set to be YES, then try to load cache before sending network request.

If cacheDuration is set to be more than 0, then write cache after receiving response object.

Flow chart of cache operation in ordinary requests:

Cache Operation

Loading cache

Loading cache of a specific network request:

[[SJNetworkManager sharedManager] loadCacheWithUrl:@"toutiao/index"
                                            method:@"POST"
                                        parameters:@{@"type":@"top",
                                                     @"key" :@"0c60"}
                                 completionBlock:^(id  _Nullable cacheObject) {                               
}];

Loading cache of network requests share the same request url:

[[SJNetworkManager sharedManager] loadCacheWithUrl:@"toutiao/index"
                                   completionBlock:^(NSArray * _Nullable cacheArr) {
}];

Loading cache of network requests which share the same request url and method:

[[SJNetworkManager sharedManager] loadCacheWithUrl:@"toutiao/index"
                                            method:@"POST"
                                   completionBlock:^(NSArray * _Nullable cacheArr) {
}];

Clearing Cache

Clearing cache of one specific network request:

[[SJNetworkManager sharedManager] clearCacheWithUrl:@"toutiao/index"
                                             method:@"POST"
                                         parameters:@{@"type":@"top",
                                                      @"key" :@"0c60"}
                                    completionBlock:^(BOOL isSuccess) {
}];

Clearing cache of network requests share the same request url:

[[SJNetworkManager sharedManager] clearCacheWithUrl:@"toutiao/index"
                                    completionBlock:^(BOOL isSuccess) {
}];

Clearing cache of network requests which share the same request url and method:

[[SJNetworkManager sharedManager] clearCacheWithUrl:@"toutiao/index"
                                             method:@"POST"
                                    completionBlock:^(BOOL isSuccess) {
}];

Calculating Cache

Calculating the size of cache folder:

[[SJNetworkManager sharedManager] calculateCacheSizeWithCompletionBlock:^(NSUInteger fileCount, NSUInteger totalSize, NSString *totalSizeString) {
        
        NSLog(@"file count :%lu and total size:%lu total size string:%@",(unsigned long)fileCount,(unsigned long)totalSize, totalSizeString);
        
}];

fileCount:file counts in cache folder

totalSize: size of cache folder(unit is byte)

totalSizeString:size of cache folder (size of unit) eg.file count :5 and total size:1298609 total size string:1.2385 MB

Uploading Function

Uploading one image, original size:

[[SJNetworkManager sharedManager]  sendUploadImageRequest:@"api"
                                               parameters:nil
                                                    image:image_1
                                                     name:@"universe"
                                                 mimeType:@"png"
                                                 progress:^(NSProgress *uploadProgress) {
                                                        
  self.progressView.observedProgress = uploadProgress;

} success:^(id responseObject) {

} failure:^(NSURLSessionTask *task, NSError *error, NSInteger statusCode, NSArray<UIImage *> *uploadFailedImages) {

}];

Here, the mimeType can be jpg/JPG, png/PNG, jpeg/JPEG and if the user gives a wrong type, the mimeType will be jpg.

Uploading two images, compress ratio is 0.5(note that if the mineType is 'png' or 'PNG', the compressRatio will be useless):

[[SJNetworkManager sharedManager]  sendUploadImagesRequest:@"api"
                                                parameters:nil
                                                    images:@[image_1,image_2]
                                             compressRatio:0.5
                                                      name:@"images"
                                                  mimeType:@"jpg"
                                                  progress:^(NSProgress *uploadProgress) {

  self.progressView.observedProgress = uploadProgress;

} success:^(id responseObject) {

} failure:^(NSURLSessionTask *task, NSError *error, NSInteger statusCode, NSArray<UIImage *> *uploadFailedImages) {
                                                    
}];

And if the server which is used for uploading is different from the server for ordinary requests, you can user this api:

[[SJNetworkManager sharedManager]  sendUploadImagesRequest:@"http://uploads.im/api"
                                               ignoreBaseUrl:YES
                                                  parameters:nil
                                                      images:@[image_1,image_2]
                                               compressRatio:0.5
                                                        name:@"images"
                                                    mimeType:@"jpg"
                                                    progress:^(NSProgress *uploadProgress) {

      self.progressView.observedProgress = uploadProgress;

  } success:^(id responseObject) {

  } failure:^(NSURLSessionTask *task, NSError *error, NSInteger statusCode, NSArray<UIImage *> *uploadFailedImages) {

  }];

Here, setting ignoreBaseUrl to be YES, and the request url should be complete download url.

Downloading Function:

We support background downloading(using NSURLSessionDownloadTask object ) and none-background downloading(using NSURLSessionDataTask object) , resumable or none-resumable downloading.

resumable none-resumable
background supporting
none-background supporting

Note:If a none-background supporting downloading is on going then app enters into background, the downloading task will be canceled. And When app enters into foreground again, an auto-resume mechanism will make the downloading task restart again.

Sending download request

Resumable && none-background supporting download reqeust (default configuration):

[[SJNetworkManager sharedManager] sendDownloadRequest:@"wallpaper.jpg"
                                     downloadFilePath:_imageFileLocalPath
                                             progress:^(NSInteger receivedSize, NSInteger expectedSize, CGFloat progress)
{
       self.progressView.progress = progress;

} success:^(id responseObject) {

} failure:^(NSURLSessionTask *task, NSError *error, NSString *resumableDataPath) {

}];

None-resumable && none-background supporting download reqeust:

[[SJNetworkManager sharedManager] sendDownloadRequest:@"half-eatch.jpg"
                                     downloadFilePath:_imageFileLocalPath
                                            resumable:NO
                                    backgroundSupport:NO
                                             progress:^(NSInteger receivedSize, NSInteger expectedSize, CGFloat progress) 
{

    self.progressView.progress = progress;

} success:^(id responseObject) {

} failure:^(NSURLSessionTask *task, NSError *error, NSString *resumableDataPath) {
    
}];

Resumable && background supporting download request:

[[SJNetworkManager sharedManager] sendDownloadRequest:@"universe.jpg"
                                     downloadFilePath:_imageFileLocalPath
                                            resumable:YES
                                    backgroundSupport:YES
                                             progress:^(NSInteger receivedSize, NSInteger expectedSize, CGFloat progress)
{

    self.progressView.progress = progress;

} success:^(id responseObject) {

} failure:^(NSURLSessionTask *task, NSError *error, NSString *resumableDataPath) {

}];

None-resumable && background supporting download request:

[[SJNetworkManager sharedManager] sendDownloadRequest:@"iceberg.jpg"
                                     downloadFilePath:_imageFileLocalPath
                                            resumable:NO
                                    backgroundSupport:YES
                                             progress:^(NSInteger receivedSize, NSInteger expectedSize, CGFloat progress)
{

    self.progressView.progress = progress;

 } success:^(id responseObject) {

 } failure:^(NSURLSessionTask *task, NSError *error, NSString *resumableDataPath) {

 }];

Also supports ignoring base url:

[[SJNetworkManager sharedManager] sendDownloadRequest:@"http://oih3a9o4n.bkt.clouddn.com/wallpaper.jpg"
                                        ignoreBaseUrl:YES
                                     downloadFilePath:_imageFileLocalPath
                                             progress:^(NSInteger receivedSize, NSInteger expectedSize, CGFloat progress)
{
      self.progressView.progress = progress;

} success:^(id responseObject) {

} failure:^(NSURLSessionTask *task, NSError *error, NSString *resumableDataPath) {

}];

Suspending download request

Suspending one download current request:

[[SJNetworkManager sharedManager] suspendDownloadRequest:@"universe.jpg"];

Suspending one or more than one current download requests:

[[SJNetworkManager sharedManager] suspendDownloadRequests:@[@"universe.jpg",@"wallpaper.jpg"]];

Suspending all current download requests:

[[SJNetworkManager sharedManager] suspendAllDownloadRequests];

Resuming download request

Resuming one download suspended request:

[[SJNetworkManager sharedManager] resumeDownloadReqeust:@"universe.jpg"];

Resuming one or more than one download requests:

[[SJNetworkManager sharedManager] resumeDownloadReqeusts:@[@"universe.jpg",@"wallpaper.jpg"]];

Resuming all current suspended requests:

[[SJNetworkManager sharedManager] resumeAllDownloadRequests];

Canceling download request

Canceling one download request:

[[SJNetworkManager sharedManager] cancelDownloadRequest:@"universe.jpg"];

Canceling one or more than one current download requests:

[[SJNetworkManager sharedManager] cancelDownloadRequests:@[@"universe.jpg",@"wallpaper.jpg"]];

Canceling all current download requests:

[[SJNetworkManager sharedManager] cancelAllDownloadRequests];

Request Management

Current request(s) Information

Checking if there is remaining current request(s):

BOOL remaining =  [[SJNetworkManager sharedManager] remainingCurrentRequests];
if (remaining) {
    NSLog(@"There is remaining request");
}

Calculating count of current request(s):

NSUInteger count = [[SJNetworkManager sharedManager] currentRequestCount];
if (count > 0) {
    NSLog(@"There is %lu requests",(unsigned long)count);
}

Logging all current request(s):

[[SJNetworkManager sharedManager] logAllCurrentRequests];

Canceling request

Canceling one network request:

[[SJNetworkManager sharedManager] cancelCurrentRequestWithUrl:@"toutiao/index"
                                                       method:@"POST"
                                                   parameters:@{@"type":@"top",
                                                                @"key" :@"0c60"}];

Canceling network request(s) with the same url:

[[SJNetworkManager sharedManager] cancelCurrentRequestWithUrl:@"toutiao/index"];

Canceling network request(s) with the same urls:

[[SJNetworkManager sharedManager] cancelDownloadRequests:@[@"toutiao/index",@"weixin/query"]];

Canceling all current network request(s):

[[SJNetworkManager sharedManager] cancelAllCurrentRequests];

Log Output

If debug mode is set to be yes, detail log will be provided:

[SJNetworkConfig sharedConfig].debugMode = YES;

Loading cache before sending network request, but cache is expired:

=========== Load cache info failed, reason:Cache is expired, begin to clear cache...
=========== Load cache failed: Cache info is invalid 
=========== Failed to load cache, start to sending network request...
=========== Start requesting...
=========== url:http://v.juhe.cn/toutiao/index
=========== method:GET
=========== parameters:{
    app_version = 1.0;
    key = 0c60;
    platform = iOS;
    type = top;
}
=========== Request succeed! 
=========== Request url:http://v.juhe.cn/toutiao/index
=========== Response object:{
  code = 200,
  msg = "",
  data = {}
}
=========== Write cache succeed!
=========== cache object: {
  code = 200,
  msg = "",
  data = {}
}
=========== Cache path: /Users/*******/
=========== Available duration: 180 seconds

Acknowledgements

Thanks for these service:

And also thanks for these two excellent framework:

Lisence

SJNetwork is released under the MIT License.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].