NSURLsession和NSURLConnection都是蘋果自帶的用于網(wǎng)絡(luò)請求的類,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 // 創(chuàng)建NSURL對象 7 NSURL *fileUrl = [NSURL fileURLWithPath:filePath]; 8 // 創(chuàng)建請求 9 NSURLRequest *request = [NSURLRequest requestWithURL:fileUrl];10 // 創(chuàng)建NSURLSession的單例11 NSURLSession *session = [NSURLSession sharedSession];12 // 創(chuàng)建一個dataTask請求數(shù)據(jù)13 NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {14 // response.MIMEType就是文件的MIMEType15 NSLog(@"%@", response.MIMEType);16 }];17 // session的任務(wù)默認是掛起的,需要手動啟用18 [dataTask resume];19 }20 // NSURLConnection版21 - (void)getMIMEType1 {22 // 用NSBundle獲取工程中文件路徑23 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"a" ofType:@"png"];24 // 創(chuàng)建NSURL對象25 NSURL *fileUrl = [NSURL fileURLWithPath:filePath];26 // 創(chuàng)建請求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 }
新聞熱點
疑難解答