Search code examples
iosresthttpalamofire

NSPOSIXErrorDomain wher download file


I have next code for download file from url. But I'm getting next error:

Failed with error: Error Domain=NSCocoaErrorDomain Code=516 "“CFNetworkDownload_85Dvq4.tmp” couldn’t be moved to “Documents” because an item with the same name already exists." UserInfo={NSSourceFilePathErrorKey=/Users/otani/Library/Developer/CoreSimulator/Devices/8BABC203-7FD9-4F03-BF0D-D660DD29CCDE/data/Containers/Data/Application/09C714D3-F185-4289-91DB-13B21557B784/tmp/CFNetworkDownload_85Dvq4.tmp, NSUserStringVariant=( Move ), NSDestinationFilePath=/Users/otani/Library/Developer/CoreSimulator/Devices/8BABC203-7FD9-4F03-BF0D-D660DD29CCDE/data/Containers/Data/Application/09C714D3-F185-4289-91DB-13B21557B784/Documents/temp.llg, NSFilePath=/Users/otani/Library/Developer/CoreSimulator/Devices/8BABC203-7FD9-4F03-BF0D-D660DD29CCDE/data/Containers/Data/Application/09C714D3-F185-4289-91DB-13B21557B784/tmp/CFNetworkDownload_85Dvq4.tmp, NSUnderlyingError=0x7fea5a53a9a0 {Error Domain=NSPOSIXErrorDomain Code=17 "File exists"}}

Code for downloading file below:

func downloadFile(let url: String!){
        self.downloadHUD()
        Alamofire.download(.GET, url) { temporaryURL, response in
            let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
            let fullPath = documentsUrl.URLByAppendingPathComponent(Misc.pathToSaveFile)
            if (NSFileManager.defaultManager().fileExistsAtPath(fullPath.absoluteString)){
                   try! NSFileManager.defaultManager().removeItemAtURL(fullPath)
            }
            return fullPath

        }
        .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
                dispatch_async(dispatch_get_main_queue()) {
                    self.hud.progress = Float(totalBytesRead) / Float(totalBytesExpectedToRead)
                    print("Total bytes read on main queue: \(totalBytesRead)")
            }
        }
        .response { _, _, _, error in
                if let error = error {
                    print("Failed with error: \(error)")
                } else {
                    print("Downloaded file successfully")
                    self.hideHUD()
                }
        }

    }

Error gets on line

print("Failed with error: \(error)")

Solution

  • Solution was rewrite deleting for destination file .