2012-08-17 125 views
0

嗨我想保存圖像到一個目錄,我通過NSData並做我認爲將文件保存在我創建的目錄中,但問題是,它不保存。這是我迄今爲止所擁有的。爲什麼沒有initWithContentsOfURL:encoding:error:work,它會返回null,但我使用的另一種方法是有效的?主要問題是WRITETOURL返回0,我認爲這意味着信息沒有正確存儲,任何提示?保存圖像到一個目錄

NSFileManager *fm = [[NSFileManager alloc] init]; 
    NSArray * directoryPaths = [fm URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask]; 
    NSLog(@"%@", directoryPaths); 
    NSURL* dirPath = nil;  
    dirPath = [[directoryPaths objectAtIndex:0] URLByAppendingPathComponent:[NSString stringWithFormat:@"photos.jpeg"]]; 
    NSError* theError = nil; 
    [fm createDirectoryAtURL:dirPath withIntermediateDirectories:YES attributes:nil error:&theError]; 

UIImage* photoToStore = [UIImage imageWithData:photoToSave]; 

NSString *pathContainingPhoto = [[NSString alloc] initWithFormat:@"%@.jpeg", UIImageJPEGRepresentation(photoToStore, 1.0)]; 
NSError *error = nil; 


BOOL OK = [pathContainingPhoto writeToURL:dirPath atomically:YES encoding:NSUTF8StringEncoding error:&error]; 

NSLog(@"OK = %d", OK); //Returns 0 
NSLog(@"%@", dirPath); 

//WHY DOESNT THIS VERSION WORK? 
// NSString *pathToFile = [[NSString alloc] initWithContentsOfURL:dirPath encoding:NSUTF8StringEncoding error:&error]; 
NSLog(@"%@", pathToFile); 

    NSString* pathToFile = [NSString stringWithContentsOfURL:dirPath encoding:nil error:nil]; 
NSArray *dirContents = [fm contentsOfDirectoryAtPath:pathToFile error:nil]; 
NSLog(@"%@", dirContents); 

回答

0

像這樣和int在.h文件中計數並設置其初始值count = 0; in viewDidLoad:

NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:[NSString stringWithFormat:@"Image_%d.png",count]; 
error = nil; 
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath]) // removing item it already exuts 
{ 
    [[NSFileManager defaultManager] removeItemAtPath:stringPath error:&error]; 
} 

if(photoToSave) // nsdata of image that u have 
{ 
    [photoToSave writeToFile:stringPath atomically:YES]; 
} 
count++; // maintaining count of images 
+0

怎麼寫writetoURL不起作用,但是writeetoFile呢? – 2012-08-17 17:12:39

+0

也它聲稱NSData不宣佈WRiteToFile? – 2012-08-17 17:23:15

+0

如果我將多個圖像保存在一個文件中,又如何獲得特定數據的內容? – 2012-08-17 17:29:53

相關問題