2011-10-04 79 views
1

當前我正在使用這些代碼將我的圖像保存到NSDocumentDirectory中。我使用這個計數器作爲他們的命名約定。從NSDocumentDirectory中檢索所有圖像並存儲到數組中

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)selectedImage editingInfo:(NSDictionary *)editingInfo 
{ 
    [self.popoverController dismissPopoverAnimated:YES]; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDir = [paths objectAtIndex:0]; 
    NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.png", counter]]; 
    UIImage *image = imageView.image; 
    NSData *imageData = UIImagePNGRepresentation(image); 
    [imageData writeToFile:savedImagePath atomically:NO]; 
} 

我使用這種方法,因爲我更容易通過使用循環來檢索它們。我想從NSDocumentDirectory中檢索所有圖像,以便我可以在另一個視圖中顯示它們。以下代碼顯示了我如何檢索它們。

-(NSMutableArray *)GetImage:(NSMutableArray *)arrayImgNames 
{ 
    NSMutableArray *tempArray; 
    for(int i=0;i<[arrayImgNames count]; i++) 
    { 
    NSArray *paths1 = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths1 objectAtIndex:0]; 
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent: [arrayImgNames objectAtIndex:i]]; 
    [tempArray addObject:[[UIImage alloc] initWithContentsOfFile:filePath]]; 
    return tempArray; 
    } 
} 

但是,我不希望使用計數器作爲我的圖像的命名約定。我想爲他們使用適當的名字,但如果我這樣做,我將不得不改變我檢索所有圖像的方法。

是否有任何其他方式,我可以檢索除了我提到的這種方法以外的所有圖像?

回答

2

可以使用另一個方法檢索文件:

NSURL *url = [[AppDelegate sharedAppDelegate] applicationDocumentsDirectory]; 
NSError *error = nil; 
NSArray *properties = [NSArray arrayWithObjects: NSURLLocalizedNameKey, NSURLLocalizedTypeDescriptionKey, nil]; 

NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:url 
        includingPropertiesForKeys:properties options:(NSDirectoryEnumerationSkipsPackageDescendants) 
        error:&error]; 

files路徑文件目錄下的所有文件將被保存。接下來的代碼將幫助你到達那裏的名字:

NSURL *url = [files objectAtIndex:index]; 
NSString *localizedName = [url lastPathComponent]; 
0

檢索NSDocumentDirectory所有圖像和存儲到的UIImageView viewcontroller.m

  • (無效)viewDidLoad中 { [超級viewDidLoad中];

    for (int i=0; i<5; i++) { 
    
    imgview=[[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)]; 
    
    NSArray *sysPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    

    NSString * docDirectory = [sysPaths objectAtIndex:0];

    NSString *str=[NSString stringWithFormat:@"img%d.jpg",i]; 
    
    NSLog(@"abc %@",str); 
    

    的NSString *的ImagePath = [docDirectory stringByAppendingPathComponent:STR];

    imgview.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:imagePath]];
    [self.view addSubview:imgview]; [imgview setUserInteractionEnabled:YES];

    x=x+width+margin; 
    if (x>=totalwidth) { 
    
        y=y+height+margin; 
        x=margin; 
    
    }  
    

    }}

相關問題