簡體   English   中英

從iPhone中的app目錄中刪除圖像

[英]Delete image from app directory in iPhone

我想從我的iPhone應用程序中刪除圖像。 我使用下面的方法,將圖像的名稱作為參數傳遞。

問題是圖像不會被刪除。

- (void)removeImage:(NSString*)fileName {

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:
                      [NSString stringWithFormat:@"%@.png", fileName]];

    [fileManager removeItemAtPath: fullPath error:NULL];
    NSLog(@"image removed: %@", fullPath);

    NSString *appFolderPath = [[NSBundle mainBundle] resourcePath];    
    NSLog(@"Directory Contents:\n%@", [fileManager directoryContentsAtPath: appFolderPath]);
}

最后兩行顯示了我的app目錄中的內容,我想要刪除的圖像仍然存在。 我究竟做錯了什么?

您正在嘗試刪除Documents目錄中的文件。 然后,您將閱讀bundle資源目錄的內容。 這些目錄不是同一個目錄。

如果您正在嘗試刪除Documents目錄中的文件,那么您最后應該在NSLog()中放置該目錄。 如果您嘗試刪除捆綁包中的文件,則無法執行此操作。 應用程序包已簽名且無法修改。

你的代碼看起來沒問題,所以嘗試在代碼中添加一些'NSError'對象:

- (void)removeImage:(NSString*)fileName {

   NSFileManager *fileManager = [NSFileManager defaultManager];
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,   YES);
   NSString *documentsDirectory = [paths objectAtIndex:0];
   NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:
                      [NSString stringWithFormat:@"%@.png", fileName]];

   NSError *error = nil;
   if(![fileManager removeItemAtPath: fullPath error:&error]) {
      NSLog(@"Delete failed:%@", error);
   } else {
      NSLog(@"image removed: %@", fullPath);
   }

   NSString *appFolderPath = [[NSBundle mainBundle] resourcePath];    
   NSLog(@"Directory Contents:\n%@", [fileManager directoryContentsAtPath: appFolderPath]);
}

在上面的代碼中,我傳遞了一個NSError錯誤參數removeItemAtPath。 如果系統無法刪除該文件,則此方法將返回NO並填充error對象並引發錯誤。

根據您的評論,我發現您正在嘗試刪除default.png並將其替換為另一個。 不幸的是,這是不可能的。 image default.png是應用程序包的一部分,一旦創建和簽名就無法修改(這是Apple的安全措施,因此應用程序在審核后無法更改)。 您可以創建和刪除文件的唯一位置是應用程序的沙箱(Documents文件夾)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM