您当前的位置: 首页 >  网络

white camel

暂无认证

  • 1浏览

    0关注

    442博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

iOS开发网络篇 一一 获取文件MIMEType的方式

white camel 发布时间:2017-12-21 00:01:57 ,浏览量:1

一共有三种方式:

// 获取MIMEType
    //1. 发送请求,可以在响应头(内部有MIMEType)
    //2. 百度 MIMEType
    //3. 调用C语言API
    //4. application/octet-stream 任意的二进制数据类型
代码如下:
//  Created by 朝阳 on 2017/12/12.
//  Copyright © 2017年 sunny. All rights reserved.
//

#import "ViewController.h"
#import 

@interface ViewController ()

@end

@implementation ViewController

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    // 获取MIMEType
    //1. 发送请求,可以在响应头(内部有MIMEType)
    //2. 百度 MIMEType
    //3. 调用C语言API
    //4. application/octet-stream 任意的二进制数据类型
    
    // [self getMimeType];
    
    NSString *mimeType = [self mimeTypeForFileAtPath:@"/Users/sunny/Desktop/test.h"];
    NSLog(@"%@",mimeType);
}

// 发送请求,在响应头中 有MIMEType属性
- (void)getMimeType
{
    //1. url
    //    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
    NSURL *url = [NSURL fileURLWithPath:@"/Users/sunny/Desktop/test.h"];
    
    //2. 创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //3. 发送异步请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        //4. 获得文件的类型
        NSLog(@"%@",response.MIMEType);
    }];
    
}

// 调用C语言API
- (NSString *)mimeTypeForFileAtPath:(NSString *)path
{
    if (![[[NSFileManager alloc] init] fileExistsAtPath:path]) {
        return nil;
    }
    
    CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[path pathExtension], NULL);
    CFStringRef MIMEType = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
    CFRelease(UTI);
    if (!MIMEType) {
        return @"application/octet-stream";
    }
    return (__bridge NSString *)(MIMEType);
}

@end

关注
打赏
1661428283
查看更多评论
立即登录/注册

微信扫码登录

0.0364s