IOS development and ios development tutorial

Source: Internet
Author: User

IOS development and ios development tutorial
ASI

The full name is ASIHTTPRequest, with the nickname "HTTP Terminator", which is very powerful.
High operating efficiency based on the underlying CFNetwork framework
Unfortunately, the author has stopped updating, and some potential bugs are not solved.
Many companies have left behind their old projects. Many previous iOS projects were named ASI + SBJson.
Whether to use ASI is one of the criteria to test whether it is a veteran iOS programmer.

Github address of ASI
Https://github.com/pokeb/asi-http-request

ASI usage reference
Http://www.cnblogs.com/dotey/archive/2011/05/10/2041966.html
Http://www.oschina.net/question/54100_36184

Send synchronous request
# Import "ASIHTTPRequest. h" // 1. Create a request NSURL * url = [NSURL URLWithString: @ "http: // 192.168.1.103: 8080/Server/login? Username = 123 & pwd = 123 "]; ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL: url]; request. timeOutSeconds = 5; // timeout // 2. send a synchronous request [request startSynchronous]; // 3. obtain the error message NSError * error = [request error]; if (error) {NSLog (@ "error ");} else {// obtain the server response NSData * data = [request responseData];} // [request responseData]
Send asynchronous request
// 1. Create a request NSURL * url = [NSURL URLWithString: @ "http: // 192.168.1.103: 8080/MJServer/login? Username = 123 & pwd = 123 "]; ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL: url]; request. timeOutSeconds = 5; // timeout // 2. set proxy request. delegate = self; // 3. send an asynchronous request [request startAsynchronous]; // ASI processes the asynchronous request by proxy. If the request succeeds or fails, the proxy is notified. // The proxy must comply with the ASIHTTPRequestDelegate protocol.
ASIHTTPRequestDelegate
// Call (void) request (ASIHTTPRequest *) request didReceiveData :( NSData *) data // call (void) requestFailed :( ASIHTTPRequest *) If the request fails *) request // call-(void) requestFinished :( ASIHTTPRequest *) request // Note: When the controller is destroyed, cancel the request [request clearDelegatesAndCancel];
SEL callback of ASI
@property (atomic, assign) SEL didStartSelector;@property (atomic, assign) SEL didReceiveResponseHeadersSelector;@property (atomic, assign) SEL willRedirectSelector;@property (atomic, assign) SEL didFinishSelector;@property (atomic, assign) SEL didFailSelector;@property (atomic, assign) SEL didReceiveDataSelector;
ASI block callback
- (void)setStartedBlock:(ASIBasicBlock)aStartedBlock;- (void)setHeadersReceivedBlock:(ASIHeadersBlock)aReceivedBlock;- (void)setCompletionBlock:(ASIBasicBlock)aCompletionBlock;- (void)setFailedBlock:(ASIBasicBlock)aFailedBlock;- (void)setBytesReceivedBlock:(ASIProgressBlock)aBytesReceivedBlock;- (void)setBytesSentBlock:(ASIProgressBlock)aBytesSentBlock;- (void)setDownloadSizeIncrementedBlock:(ASISizeBlock) aDownloadSizeIncrementedBlock;- (void)setUploadSizeIncrementedBlock:(ASISizeBlock) anUploadSizeIncrementedBlock;- (void)setDataReceivedBlock:(ASIDataBlock)aReceivedBlock;- (void)setAuthenticationNeededBlock:(ASIBasicBlock)anAuthenticationBlock;- (void)setProxyAuthenticationNeededBlock:(ASIBasicBlock)aProxyAuthenticationBlock;- (void)setRequestRedirectedBlock:(ASIBasicBlock)aRedirectBlock;typedef void (^ASIBasicBlock)(void);typedef void (^ASIHeadersBlock)(NSDictionary *responseHeaders);typedef void (^ASISizeBlock)(long long size);typedef void (^ASIProgressBlock)(unsigned long long size, unsigned long long total);typedef void (^ASIDataBlock)(NSData *data);
Obtain Server Response
// Obtain the status code \ status information @ property (atomic, assign, readonly) int responseStatusCode; @ property (atomic, retain, readonly) NSString * responseStatusMessage; // obtain the Response Header @ property (atomic, retain) NSDictionary * responseHeaders; // obtain the object content (response body)-(NSData *) responseData;-(NSString *) responseString;
Send POST request
Include header file: # import "ASIFormDataRequest. h "// 1. create a request NSURL * url = [NSURL URLWithString: @ "http: // 192.168.1.103: 8080/Server/login"]; ASIFormDataRequest * request = [ASIFormDataRequest requestWithURL: url]; // 2. set the request parameter [request addPostValue: @ "123" forKey: @ "username"]; [request addPostValue: @ "123" forKey: @ "pwd"]; // note the difference between addPostValue and setPostValue
File Upload
ASIFormDataRequest * request = [ASIFormDataRequest requestWithURL: url]; // Add a common request parameter [request addPostValue: @ "MJ" forKey: @ "username"]; // Add the file parameter NSString * file = [[NSBundle mainBundle] pathForResource: @ "musicplayer.png" ofType: nil]; [request addFile: file forKey: @ "file"]; // or UIImage * image = [UIImage imageNamed: @ "musicplayer"]; NSData * data = UIImagePNGRepresentation (image); [request addData: data withFileName: @ "test.png" andContentType: @ "image/png" forKey: @ "file"]; there are two ways to add file parameters // use the full path of the file-(void) addFile :( NSString *) filePath forKey :( NSString *) key-(void) addFile :( NSString *) filePath withFileName :( NSString *) fileName andContentType :( NSString *) contentType forKey :( NSString *) key // pass the specific data of the file-(void) addData :( id) data withFileName :( NSString *) fileName andContentType :( NSString *) contentType forKey :( NSString *) key
File Download
// Set the cache path NSString * caches = [Response (NSCachesDirectory, NSUserDomainMask, YES) lastObject]; NSString * filepath = [caches stringByAppendingPathComponent: @ "test.mp4"]; request. downloadDestinationPath = filepath; // sets the download proxy request. downloadProgressDelegate = self. progressView; supports resumable upload of large files // sets the temporary file path request. temporaryFileDownloadPath = tmpFilepath; // supports resumable upload request. allowResumeForFileDownloads = YES;
Listener file upload/download progress
// Become the ASI proxy-(void) setUploadProgressDelegate :( id) newDelegate // follow the ASIProgressDelegate Protocol to implement the Protocol method-(void) setProgress :( float) newProgress;
Cache

ASI also provides the data cache Function
It only caches the response data of the Get request.
The cached data must be a successful 200 request.
Use the ASIDownloadCache class to manage the cache

Common ASIDownloadCache usage

// Obtain the default cache object ASIDownloadCache * cache = [ASIDownloadCache sharedCache]; // set the cache policy-(void) setDefaultCachePolicy :( ASICachePolicy) cachePolicy // set the cache path-(void) setStoragePath :( NSString *) path

Cache Policy: When to cache and how to use cached data. Available in combination
Default Cache Policy: If no expired cache data exists, the cache is used; otherwise, network requests are made to determine whether the server version is the same as the local version. If the server version is the same, the cache is used. If the server has a new version, a network request is sent and

// The new local cache scheme is roughly the same as the default cache. The difference is that each request goes to the server to determine whether there is an update. ASIAskServerIfModifiedCachePolicy does not read cached data. // ASIDoNotReadFromCacheCachePolicy // No cached data, do not write the cache ASIDoNotWriteToCacheCachePolicy // if there is a cache, no matter whether it expires or not, it will always be used. If there is no cache, The ASIOnlyLoadIfNotCachedCachePolicy will be requested again for use. If no cache, the request will be canceled (no error message) ASIDontLoadCachePolicy // when the request fails, if there is a cache, it will return the cache (often used in combination with other options) ASIFallbackToCacheIfLoadFailsCachePolicy
Cache a request
// Set the cache Policy ASIDownloadCache * cache = [ASIDownloadCache sharedCache]; [cache setDefaultCachePolicy: ASIOnlyLoadIfNotCachedCachePolicy | cached]; // use the cache [request setDownloadCache: cache]; // set the cache storage policy (permanent storage) [request setCacheStoragePolicy: ASICachePermanentlyCacheStoragePolicy]; // set the cache Policy ASIDownloadCache * cache = [ASIDownloadCache sharedCache]; [cache setDefaultCachePolicy: ASIOnlyLoadIfNotCachedCachePolicy | ASIFallbackToCacheIfLoadFailsCachePolicy]; // use the cache [ASIHTTPRequest setDefaultCache: cache];
Other usage
Whether a network request is being processed [ASIHTTPRequest isNetworkInUse]; Whether to display the network status (circled) in the status bar when the request is being processed [ASIHTTPRequest setShouldUpdateNetworkActivityIndicator: YES]; when the application is running in the background, whether to continue to process the network request. shouldContinueWhenAppEntersBackground = YES; set the number of retries after request timeout request. numberOfTimesToRetryOnTimeout = 2; // retry twice

Related Article

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.