ios开发网络学习五:MiMEType ,多线程下载文件思路,文件的压缩和解压缩

一:MiMEType:一般可以再百度上搜索到相应文件的MiMEType,或是利用c语言的api去获取文件的MiMEType

//对该文件发送一个异步请求,拿到文件的MIMEType

- (void)MIMEType

{

    //    NSString *file = @"file:///Users/文顶顶/Desktop/test.png";

    [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:@"/Users/文顶顶/Desktop/test.png"]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * __nullable response, NSData * __nullable data, NSError * __nullable connectionError) {

        //       response.MIMEType

        NSLog(@"%@",response.MIMEType);

    }];

}

```

(2)通过UTTypeCopyPreferredTagWithClass方法

```objc

//注意:需要依赖于框架MobileCoreServices

- (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);

}

```

二:多线程文件下载思路:将下载文件分成若干段,每段任务创建一条线程,多个任务并发执行下载文件的操作,不能利用输出流进行文件二进制数据data的拼接,否则会出现数据错乱。利用文件句柄,在代理方法中,接受到数据后,判断是哪条线程,再根据线程的不同,将文件句柄的位置偏移到seekoffset,偏移到相应线程的下载的地方

三:文件的压缩和解压缩

#import "ViewController.h"
#import "SSZipArchive.h"

@interface ViewController ()

@end

@implementation ViewController
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self unzip];
}

-(void)zip
{
    NSArray *arrayM = @[
                        @"/Users/xiaomage/Desktop/Snip20160226_2.png",
                        @"/Users/xiaomage/Desktop/Snip20160226_6.png"
                        ];
    /*
     第一个参数:压缩文件的存放位置
     第二个参数:要压缩哪些文件(路径)
     */
    //[SSZipArchive createZipFileAtPath:@"/Users/xiaomage/Desktop/Test.zip" withFilesAtPaths:arrayM];
    [SSZipArchive createZipFileAtPath:@"/Users/xiaomage/Desktop/Test.zip" withFilesAtPaths:arrayM withPassword:@"123456"];
}

-(void)zip2
{
    /*
     第一个参数:压缩文件存放位置
     第二个参数:要压缩的文件夹(目录)
     */
    [SSZipArchive createZipFileAtPath:@"/Users/xiaomage/Desktop/demo.zip" withContentsOfDirectory:@"/Users/xiaomage/Desktop/demo"];
}

-(void)unzip
{
    /*
     第一个参数:要解压的文件在哪里
     第二个参数:文件应该解压到什么地方
     */
    //[SSZipArchive unzipFileAtPath:@"/Users/xiaomage/Desktop/demo.zip" toDestination:@"/Users/xiaomage/Desktop/xx"];
    
    [SSZipArchive unzipFileAtPath:@"/Users/xiaomage/Desktop/demo.zip" toDestination:@"/Users/xiaomage/Desktop/xx" progressHandler:^(NSString *entry, unz_file_info zipInfo, long entryNumber, long total) {
        NSLog(@"%zd---%zd",entryNumber,total);
        
    } completionHandler:^(NSString *path, BOOL succeeded, NSError *error) {
        
        NSLog(@"%@",path);
    }];
}


@end
原文地址:https://www.cnblogs.com/cqb-learner/p/5862059.html