包括四個會話
- 簡單會話-通過NSURLSession靜態(tài)方法+sharedSession獲得NSURLSession對象
NSString *strURL = [[NSString alloc] initWithFormat:@"http://xxx/WebService.php?email=%@&type=%@&action=%@", @"xxx@xxx.com", @"JSON", @"query"];
strURL = [strURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];//將字符串轉(zhuǎn)化成URL字符串,例如"<"的URL編碼是"%3C"
NSURL *url = [NSURL URLWithString:strURL];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"請求完成...");
if (!error) {
NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
dispatch_async(dispatch_get_main_queue(), ^{
[self reloadView:resDict];
});
} else {
NSLog(@"error : %@", error.localizedDescription);
}
}];
[task resume];
- 默認(rèn)會話(default session)-通過NSURLSession靜態(tài)方法+sessionWithConfiguration:或者+sessionWithConfiguration:delegate:delegateQueue:獲得NSURLSession對象
1,以下為GET方法請求數(shù)據(jù)
NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration: defaultConfig delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
2,以下是POST請求,GET請求是NSURLRequest,POST請求是NSMutableURLRequest
NSString *strURL = @"http://xxx/WebService.php";
NSURL *url = [NSURL URLWithString:strURL];
NSString *post = [NSString stringWithFormat:@"email=%@&type=%@&action=%@", @"xxx@xxx.com", @"JSON", @"query"];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration: defaultConfig delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"請求完成...");
if (!error) {
NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
[self reloadView:resDict];
} else {
NSLog(@"error : %@", error.localizedDescription);
}
}];
[task resume];
3,下載圖片
- (IBAction)onClick:(id)sender {
NSString *strURL = [[NSString alloc] initWithFormat:@"http://xxx/download.php?email=%@&FileName=test1.jpg", @"xxx@xxx.com"];
NSURL *url = [NSURL URLWithString:strURL];
NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:defaultConfig delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:url];
[downloadTask resume];
}
#pragma mark -- 實現(xiàn)NSURLSessionDownloadDelegate委托協(xié)議
//下載中的方法,可以用來改變下載進(jìn)度條
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
float progress = totalBytesWritten * 1.0 / totalBytesExpectedToWrite;
[self.progressView setProgress:progress animated:TRUE];
NSLog(@"進(jìn)度= %f", progress);
NSLog(@"接收: %lld 字節(jié) (已下載: %lld 字節(jié)) 期待: %lld 字節(jié).", bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
}
//下載完成後調(diào)用的方法
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
NSLog(@"臨時文件: %@\n", location);
NSString *downloadsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, TRUE) objectAtIndex:0];
NSString *downloadStrPath = [downloadsDir stringByAppendingPathComponent:@"test1.jpg"];
NSURL *downloadURLPath = [NSURL fileURLWithPath:downloadStrPath];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
if ([fileManager fileExistsAtPath:downloadStrPath]) {
[fileManager removeItemAtPath:downloadStrPath error:&error];
if (error) {
NSLog(@"刪除文件失敗: %@", error.localizedDescription);
}
}
error = nil;
if ([fileManager moveItemAtURL:location toURL:downloadURLPath error:&error]) {
NSLog(@"文件保存: %@", downloadStrPath);
UIImage *img = [UIImage imageWithContentsOfFile:downloadStrPath];
self.imageView1.image = img;
} else {
NSLog(@"保存文件失敗: %@", error.localizedDescription);
}
}
- 短暫會話(ephemeral session)-通過NSURLSessionConfiguration靜態(tài)方法+ephemeralSessionConfiguration獲得
- 後臺會話(background session)-通過NSURLSessionConfiguration靜態(tài)方法+backgroundSessionConfigurationWithIdentifier:獲得
包括三種形式的任務(wù)
- 數(shù)據(jù)任務(wù)(data task) NSURLSessionDataTask類
- 上傳任務(wù)(upload task) NSURLSessionUploadTask類
- 下載任務(wù)(download task) NSURLSessionDownloadTask類