2017-02-15 39 views
1

我有一個功能可以將文件成功移動到共享應用程序組中,但我的刪除該文件的功能似乎不起作用。如果我打印出fullpath2變量,它看起來是正確的位置,但文件不會被刪除,並且不會返回錯誤。從共享應用程序組中刪除文件

這裏是我的功能:

func getSharedFilePath(appGroup:String,sharedFilename:String)->URL? { 

if let directoryPath = FileManager().containerURL(forSecurityApplicationGroupIdentifier: appGroup) { 
    return directoryPath.appendingPathComponent(sharedFilename) 
} else { 
    return nil 
} 
} 


public func deleteFromSharedFile(sharedFilename: String, fileExtension: String)->String { 
let sharedFilename = "\(sharedFilename).\(fileExtension)" 
guard let url = getSharedFilePath(appGroup:applicationGroup,sharedFilename:sharedFilename) else { 
    return("Error getting shared file path") 
} 

// read file from file system to data variable 
let fileManager = FileManager.default 
do { 
    try fileManager.removeItem(atPath: (url.path)) 
    return("File Removed") 
} 
catch let error as NSError { 
    return("File Remove Failed - \(error)") 
} 
} 
+0

'url.absoluteString'錯誤。你需要找到它的路徑。 '嘗試fileManager.removeItem(atPath:url.path)'。 BTW absoluteString也會返回url方案(在這種情況下爲'file://'),並且您正在添加它並將它移除到下一行。 –

+0

@LeoDabus使用url.path無效 – Nate23VT

+0

用您的實際代碼更新您的問題 –

回答

2

這裏是我的表情符號的應用程序的一些代碼段。

它運作良好。

func removeImage(itemName: String, fileExtension: String) { 
    let fileName:String = itemName + "." + fileExtension 
    let fileManager = FileManager.default 
    guard let groupURL = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.io.XXXXXX.XXXX") else { 
     return 
    } 
    let storagePathUrl = groupURL.appendingPathComponent("image/" + fileName, isDirectory: false) 
    let storagePath = storagePathUrl.path 

    do { 
     if fileManager.fileExists(atPath: storagePath) { 
      try fileManager.removeItem(atPath: storagePath) 
     } 
    } catch let error as NSError { 
     print(error.debugDescription) 
    } 
} 

「image」只是應用程序組的子文件夾的名稱。

如果您將文件直接保存在根文件夾中,則可以將其刪除。

希望它可以幫助你。

相關問題