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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM