·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> 用NSURLSession和NSURLConnection获取文件的MIMEType

用NSURLSession和NSURLConnection获取文件的MIMEType

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23
NSURLsession和NSURLConnection都是苹果自带的用于网络请求的类,NSURLSession是iOS 7.0之后推出的用于替代NSURLConnection的。下面分享一下这两个类获取文件MIMEType的方法。
 1 #PRagma mark 获取文件的mimeType
 2 // NSURLSession版
 3 - (void)getMIMEType {
 4     // 用NSBundle获取工程中文件路径
 5     NSString *filePath = [[NSBundle mainBundle] pathForResource:@"a" ofType:@"png"];
 6     // 创建NSURL对象
 7     NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
 8     // 创建请求
 9     NSURLRequest *request = [NSURLRequest requestWithURL:fileUrl];
10     // 创建NSURLSession的单例
11     NSURLSession *session = [NSURLSession sharedSession];
12     // 创建一个dataTask请求数据
13     NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
14         // response.MIMEType就是文件的MIMEType
15         NSLog(@"%@", response.MIMEType);
16     }];
17     // session的任务默认是挂起的,需要手动启用
18     [dataTask resume];
19 }
20 // NSURLConnection版
21 - (void)getMIMEType1 {
22     // 用NSBundle获取工程中文件路径
23     NSString *filePath = [[NSBundle mainBundle] pathForResource:@"a" ofType:@"png"];
24     // 创建NSURL对象
25     NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
26     // 创建请求
27     NSURLRequest *request = [NSURLRequest requestWithURL:fileUrl];
28     NSURLResponse *response = nil;
29     // 同步请求
30     [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
31     // response.MIMEType就是文件的MIMEType
32     NSLog(@"%@", response.MIMEType);
33 }