Network development tools for IOS development
Network development tools for IOS development
Mobile development usually involves several modules: 1. network detection 2. Network request get and post requests 3. File Upload 4. File Download 5. resumable upload
Now I will share these with you one by one. You are also welcome to study and discuss this example using the AFNetWorking framework.
Network detection:
# Pragma mark-Reachability Management (iOS 6-7)
// Network listener (used to check whether the network can be connected. This method is recommended in AppDelegate to enable the program to start network detection)
-(Void) reachabilityManager
{
// Enable the network listener
[Manager. reachabilityManager startMonitoring];
// Listen for network changes
[Manager. reachabilityManager setReachabilityStatusChangeBlock: ^ (AFNetworkReachabilityStatus status ){
Switch (status ){
// When the network is unavailable (no network or request delay)
Case AFNetworkReachabilityStatusNotReachable:
Break;
// When mobile phone cellular data network and WiFi
Case AFNetworkReachabilityStatusReachableViaWiFi:
Case AFNetworkReachabilityStatusReachableViaWWAN:
Break;
// Other cases
Default:
Break;
}
}];
// Stop the network listener (if you need to continuously check the network status, you can keep it running without stopping)
[Manager. reachabilityManager stopMonitoring];
}
Get request data:
# Pragma mark-GET Request (iOS 6-7)
// GET request
-(Void) methodGet
{
// Empty request
If (manager ){
Manager = nil;
}
// Create a request
Manager = [AFHTTPRequestOperationManager];
// Set the request parser to AFHTTPResponseSerializer (used to directly parse NSData). The default value is AFJSONResponseSerializer (used to parse JSON)
// Manager. responseSerializer = [AFHTTPResponseSerializer serializer];
// Send a GET request
[Manager GET: @ "interface address" parameters: nil success: ^ (AFHTTPRequestOperation * operation, id responseObject ){
// Request succeeded (when the parser is AFJSONResponseSerializer)
NSLog (@ "Success: % @", responseObject );
// Request succeeded (when the parser is AFHTTPResponseSerializer)
// NSString * JSONString = [[NSString alloc] initWithData: responseObject encoding: NSUTF8StringEncoding];
// NSLog (@ "success: % @", JSONString );
} Failure: ^ (AFHTTPRequestOperation * operation, NSError * error ){
// Request failed
NSLog (@ "Error: % @", error );
}];
}
POST request:
# Pragma mark-POST Request (iOS 6-7)
// POST request
-(Void) methodPost
{
// Empty request
If (manager ){
Manager = nil;
}
// Add Parameters
NSDictionary * parameters =@ {@ "Key": @ "Object ",
@ "Key": @ "Object "};
// Create a request
Manager = [AFHTTPRequestOperationManager];
// Set the request parser to AFHTTPResponseSerializer (used to directly parse NSData). The default value is AFJSONResponseSerializer (used to parse JSON)
// Manager. responseSerializer = [AFHTTPResponseSerializer serializer];
// Send a POST request
[Manager POST: @ "interface address" parameters: parameters success: ^ (AFHTTPRequestOperation * operation, id responseObject ){
// Request succeeded (when the parser is AFJSONResponseSerializer)
NSLog (@ "Success: % @", responseObject );
// Request succeeded (when the parser is AFHTTPResponseSerializer)
// NSString * JSONString = [[NSString alloc] initWithData: responseObject encoding: NSUTF8StringEncoding];
// NSLog (@ "success: % @", JSONString );
} Failure: ^ (AFHTTPRequestOperation * operation, NSError * error ){
// Request failed
NSLog (@ "Error: % @", error );
}];
}
Upload:
# Pragma mark-Upload Request (iOS 6-7)
// Upload (upload using a form, taking an image as an example)
-(Void) methodUpload
{
// Empty request
If (manager ){
Manager = nil;
}
// Add Parameters
NSDictionary * parameters =@ {@ "Key": @ "Object ",
@ "Key": @ "Object "};
// Create a request
Manager = [AFHTTPRequestOperationManager];
// Set the request parser to AFHTTPResponseSerializer (used to directly parse NSData). The default value is AFJSONResponseSerializer (used to parse JSON)
// Manager. responseSerializer = [AFHTTPResponseSerializer serializer];
// Send a POST request to add the file to be sent, which is an image
[Manager POST: @ "interface address" parameters: parameters constructingBodyWithBlock: ^ (id formData ){
// Add an image and compress it (0.0 is the maximum compression rate and 1.0 is the minimum compression rate)
NSData * imageData = UIImageJPEGRepresentation ([UIImage imageNamed: @ "image name (note the suffix name)"], 1.0 );
// Add the file to be uploaded. The image is shown here.
[FormData appendPartWithFileData: imageData name: @ "parameter name of the server image (Key)" fileName: @ "image name" mimeType: @ "file type (image format is used here, for example, image/jpeg) "];
} Success: ^ (AFHTTPRequestOperation * operation, id responseObject ){
// Request succeeded (when the parser is AFJSONResponseSerializer)
NSLog (@ "Success: % @", responseObject );
// Request succeeded (when the parser is AFHTTPResponseSerializer)
// NSString * JSONString = [[NSString alloc] initWithData: responseObject encoding: NSUTF8StringEncoding];
// NSLog (@ "success: % @", JSONString );
} Failure: ^ (AFHTTPRequestOperation * operation, NSError * error ){
// Request failed
NSLog (@ "Error: % @", error );
}];
}
Download:
# Pragma mark-Download Request (iOS 6-7)
// Download
-(Void) methodDownload
{
// Download progress bar
UIProgressView * downProgressView = [[UIProgressView alloc] initWithProgressViewStyle: UIProgressViewStyleDefault];
DownProgressView. center = CGPointMake (self. view. center. x, 220 );
DownProgressView. progress = 0;
DownProgressView. progressTintColor = [UIColor blueColor];
DownProgressView. trackTintColor = [UIColor grayColor];
[Self. view addSubview: downProgressView];
// Set the file storage location (this Demo saves the file in the Documents folder in the iPhone sandbox. For information on how to obtain the file path, search for relevant information)
// Method 1
// NSArray * paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES );
// NSString * cachesDirectory = [paths objectAtIndex: 0];
// NSString * filePath = [cachesDirectory stringByAppendingPathComponent: @ "file name"];
// Method 2
NSString * filePath = [NSString stringWithFormat: @ "% @/Documents/file name (note the suffix)", NSHomeDirectory ()];
// Print the file storage path
NSLog (@ "% @", filePath );
// CREATE request management
Operation = [[AFHTTPRequestOperation alloc] initWithRequest: [NSURLRequest requestWithURL: [NSURL URLWithString: @ ""];
// Add a download request (obtain the output stream of the server)
Operation. outputStream = [NSOutputStream outputStreamToFileAtPath: filePath append: NO];
// Set the download progress bar
[Operation setDownloadProgressBlock: ^ (NSUInteger bytesRead, long totalBytesRead, long totalBytesExpectedToRead ){
// Display the download progress
CGFloat progress = (float) totalBytesRead)/totalBytesExpectedToRead;
[DownProgressView setProgress: progress animated: YES];
}];
// Request management determines request results
[Operation setCompletionBlockWithSuccess: ^ (AFHTTPRequestOperation * operation, id responseObject ){
// The request is successful.
NSLog (@ "Finish and Download to: % @", filePath );
} Failure: ^ (AFHTTPRequestOperation * operation, NSError * error ){
// Request failed
NSLog (@ "Error: % @", error );
}];
}
Resumable upload:
# Pragma mark-Download Management (iOS 6-7)
// Start download (resumable upload)
-(Void) downloadStart
{
[Self methodDownload];
[Operation start];
}
// Pause download (resumable download)
-(Void) downloadPause
{
[Operation pause];
}
// Continue download (resumable download)
-(Void) downloadResume
{
[Operation resume];
}
Unique upload and download features of IOS7:
# Pragma mark-Upload Request (iOS 7 only)
// Upload (for iOS7)
-(Void) methodUploadFor7
{
// Empty request
If (sessionManager ){
SessionManager = nil;
}
// Create a request (dedicated to iOS7)
SessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration: [NSURLSessionConfiguration defaultSessionConfiguration];
// Add request Interface
NSURLRequest * request = [NSURLRequest requestWithURL: [NSURL URLWithString: @ "Upload address"];
// Add an uploaded file
NSURL * filePath = [NSURL fileURLWithPath: @ "local file address"];
// Send an upload request
NSURLSessionUploadTask * uploadTask = [sessionManager uploadTaskWithRequest: request fromFile: filePath progress: nil completionHandler: ^ (NSURLResponse * response, id responseObject, NSError * error ){
If (error ){
// Request failed
NSLog (@ "Error: % @", error );
} Else {
// The request is successful.
NSLog (@ "Success: % @", response, responseObject );
}
}];
// Start upload
[UploadTask resume];
}
# Pragma mark-Download Request (iOS 7 only)
// Download (for iOS7)
-(Void) methodDownloadFor7
{
// Empty request
If (sessionManager ){
SessionManager = nil;
}
// Create a request (dedicated to iOS7)
SessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration: [NSURLSessionConfiguration defaultSessionConfiguration];
// Add request Interface
NSURLRequest * request = [NSURLRequest requestWithURL: [NSURL URLWithString: @ ""];
// Send a download request
NSURLSessionDownloadTask * downloadTask = [sessionManager downloadTaskWithRequest: request progress: nil destination: ^ NSURL * (NSURL * targetPath, NSURLResponse * response ){
// Set the file storage location (this Demo saves the file in the Documents folder in the iPhone sandbox. For information on how to obtain the file path, search for relevant information)
NSURL * filePath = [NSURL fileURLWithPath: [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
Return [filePath URLByAppendingPathComponent: [response suggestedFilename];
} CompletionHandler: ^ (NSURLResponse * response, NSURL * filePath, NSError * error ){
// Download complete
NSLog (@ "Finish and Download to: % @", filePath );
}];
// Start download
[DownloadTask resume];
}
Source code: http://download.csdn.net/detail/wangliang198901/7935199