About NSURLSession upload and download
After IOS7.0, Apple released a new NSURLSession to replace NSURLConnection. NSURLConnection is executed in the main thread by default. The NSURLSession is executed on other threads. This article mainly implements download and upload, which is easier than NSURLConnection. Thread control is clearer.
# Pragma mark-Download
-(IBAction) DownLoad
{
// 1.URL
NSString * urlStr = @ "http://she.21cn.com/emotions/mingren/a/2014/0309/15/26645767.shtml ";
NSURL * url = [NSURL URLWithString: urlStr];
// 2. NSURLRequest
NSURLRequest * request = [NSURLRequestrequestWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicytimeoutInterval: 5.0];
// 3. NSURLSession
NSURLSession * session = [NSURLSessionsharedSession];
NSURLSessionDownloadTask * downLoad = [session downloadTaskWithRequest: request completionHandler: ^ (NSURL * location, NSURLResponse * response, NSError * error ){
If (error ){
NSLog (@ "error = % @", error. localizedDescription );
} Else {
// Location is the directory of the downloaded temporary file
NSLog (@ "% @", location );
// If you want to save the file, you need to save the file to the sandbox
// 1. Get the downloaded file name based on the URL
NSString * fileName = [urlStr lastPathComponent];
// 2. Generate the sandbox path
NSArray * docs = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES );
NSString * path = [docs [0] stringByAppendingPathComponent: fileName];
NSURL * toURL = [NSURL fileURLWithPath: path];
// 3. copy the file from the temporary folder to the sandbox. All file operations on iOS use NSFileManager.
[[NSFileManager defaultManager] copyItemAtURL: location toURL: toURL error: nil];
// 4. Set the image to UIImageView
Dispatch_async (dispatch_get_main_queue (), ^ {
UIImage * image = [[UIImage alloc] initWithContentsOfFile: path];
_ ImageView. image = image;
});
}
}];
// 4. because the task is suspended by default, You need to resume the task (execute the task)
[DownLoad resume];
}
-(IBAction) upLoad
{
// 0. Determine whether the imageView has content
If (_ imageView. image = nil ){
NSLog (@ "image view is empty ");
Return;
}
// 0. Add an indicator on the interface before uploading
UIActivityIndicatorView * indicator = [[UIActivityIndicatorViewalloc] initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleGray];
// Set the location ???
CGSize size = _ imageView. bounds. size;
Indicator. center = CGPointMake (size. width/2.0, size. height/2.0 );
[Self. imageView addSubview: indicator];
[Indicator startAnimating];
// 1. URL
NSString * urlStr = @ "http: // 192.168.3.20./ uploads/123.jpg ";
NSURL * url = [NSURL URLWithString: urlStr];
// 2. Request-> PUT. The default request operation is GET.
NSMutableURLRequest * request = [NSMutableURLRequestrequestWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicytimeoutInterval: 5.0f];
Request. HTTPMethod = @ "PUT ";
// *** Set the authentication for network requests! ***
// 1> authorization string
NSString * authStr = @ "admin: 123456 ";
// 2> BASE64 encoding to prevent plaintext transmission of data over the network
// In iOS, only BASE64 encoding is supported for NSData-type data
NSData * authData = [authStr dataUsingEncoding: NSUTF8StringEncoding];
NSString * encodeStr = [authData base64encodedstringwitexceptions: NSDataBase64EncodingEndLineWithCarriageReturn];
NSString * authValue = [NSString stringWithFormat: @ "Basic % @", encodeStr];
[Request setValue: authValue forHTTPHeaderField: @ "Authorization"];
// 3. Session
NSURLSession * session = [NSURLSessionsharedSession];
// 4. UploadTask
NSData * imageData = UIImageJPEGRepresentation (_ imageView. image, 0.75 );
NSURLSessionUploadTask * upload = [session uploadTaskWithRequest: request fromData: imageData completionHandler: ^ (NSData * data, NSURLResponse * response, NSError * error ){
// After the upload is complete, the data parameter is converted to string, which is the content returned by the server.
NSString * str = [[NSStringalloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (@ "OK-> % @", str );
If (error! = Nil ){
NSLog (@ "ERROR-> % @", error. localizedDescription );
} Else {
}
[NSThreadsleepForTimeInterval: 5.0f];
Dispatch_async (dispatch_get_main_queue (), ^ {
[Indicator stopAnimating];
[Indicator removeFromSuperview];
});
}];
[Upload resume];
}