iOS 获取本地文件的各种坑

1.无论:TXT,EPUB,PDF等各种格式的文件,保存到本地的时候,最好都保存成字母或者数字,不要保存成汉字,否则,在取文件的时候,由于编码的问题,各种瓦特

2.如果文件名真的保存成了汉字,那么进行转码的方法是:

[fileName
                                                                       stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];//不这样处理会返回nil];

3.pdf的坑:由于后台返回的文件格式都是dat,需要本地动态判断文件格式,因此在判断PDF的时候,就遇到了很多问题

       1. 在NSURL和filePath之间转换的时候,虽然filePath是一个string,但是不能用URL.absoluteString这个方法,应该用URL.path 这个方法,不然后面取不到文件

          string转URL的时候,这样:

[NSURL URLWithString:_model.filePath]

 

       2,把文件路径中的.dat 替换成 .pdf,没卵用:

[aFilePath  stringByReplacingOccurrencesOfString:@".dat" withString:@".pdf"]

      必须重命名文件名

//获取本地的PDF文件
+(CGPDFDocumentRef)pdfRefByFilePath:(NSString *)aFilePath
{
//     CFURLRef pdfURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), (__bridge CFStringRef)[aFilePath lastPathComponent], NULL, (__bridge CFStringRef)@"files");
//    CGPDFDocumentRef pdfDocument = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
//    
    CFStringRef path;
    CFURLRef url;
    CGPDFDocumentRef document;
    size_t count;
    
    //pdf的扩展名必须重命名一下,才可以取到
    NSString* aFilePath2 = [aFilePath  stringByReplacingOccurrencesOfString:@".dat" withString:@".pdf"];
    NSError* error;
    //[[NSFileManager defaultManager] moveItemAtPath:aFilePath2 toPath:aFilePath2 error:nil];
    NSFileManager* fileManager =[NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:aFilePath]) {
        //get new resource path with different extension
        
        //copy it over
        [fileManager copyItemAtPath:aFilePath toPath:aFilePath2 error:&error];
    }
    
    path = CFStringCreateWithCString (NULL, [aFilePath2   UTF8String],
                                      kCFStringEncodingUTF8);
    url = CFURLCreateWithFileSystemPath (NULL, path,
                                         kCFURLPOSIXPathStyle, 0);
    CFRelease (path);
    document = CGPDFDocumentCreateWithURL (url);
    CFRelease(url);
    if (document == nil) {
        [fileManager copyItemAtPath:aFilePath2 toPath:aFilePath error:&error];
    }
    
    
//    NSString* filePath = [aFilePath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    CFStringRef path;
//    CFURLRef url;
//    CGPDFDocumentRef document;
//    filePath = [aFilePath  stringByReplacingOccurrencesOfString:@".dat" withString:@".pdf"];
//    path = CFStringCreateWithCString(NULL, [filePath UTF8String], kCFStringEncodingUTF8);
//    url = CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, 0);
//    CFRelease(path);
//    document = CGPDFDocumentCreateWithURL(url);
//    CFRelease(url);
    
    return document;
    
}

 

转载于:https://www.cnblogs.com/lucky-star-star/p/5865752.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值