首页 > 学院 > 开发设计 > 正文

用NSURLSession和NSURLConnection获取文件的MIMEType

2019-11-14 19:38:37
字体:
来源:转载
供稿:网友
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就是文件的MIMEType15         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就是文件的MIMEType32     NSLog(@"%@", response.MIMEType);33 }

 

 

 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表