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;
    
}

 

posted @ 2016-09-12 18:15  伟大的臭猪猪  阅读(8723)  评论(0编辑  收藏  举报