I try to download mp3 files the in iPhone with swift. But those files are SOMETIMES damaged. (The duration time of downloaded Mp3 is changed due to this problem. so it can not read the right duration time in MPmovieplayer) I don't know why. Can you help me to solve the problems?
func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse)
{
self.totalByte = self.totalByte + Double(response.expectedContentLength)
self.delegate?.onDownLoadStart?(self.fileId,filePath:self.savePath, fileLength: self.totalByte,loadPath:self.filePath, info:self.info!)
}
func connection(connection: NSURLConnection, didReceiveData data: NSData)
{
if(self.isSaved){
if(self.bigFile == nil){
if(self.file != nil){
self.file!.appendData(data)
}
self.bigFile = NSFileHandle(forUpdatingAtPath: self.savePath)
self.file = nil
}else{
self.bigFile!.seekToEndOfFile()
self.bigFile!.writeData(data)
}
self.progressByte = progressByte + Double(data.length)
}else{
if(self.file == nil){
self.file = NSMutableData()
}
self.file!.appendData(data)
progressByte = Double(file!.length)
}
self.delegate?.onDownLoadProgress?(self.fileId, progressPct:Float(self.progressByte/self.totalByte))
}
func connectionDidFinishLoading(connection: NSURLConnection){
self.delegate?.onDownLoadComplete(self.fileId, filePath:self.savePath, fileData:self.file,loadPath:self.filePath, info: self.info!)
self.removeFileHandle()
}
private func removeFileHandle()
{
bigFile?.closeFile()
bigFile=nil;
file=nil;
}
func connection(connection: NSURLConnection, didFailWithError error: NSError){
print("DownLoader path="+self.filePath+" errorCode="+error.code.description);
self.removeFileHandle()
self.delegate?.onDownLoadError?(self.fileId,filePath:self.savePath, withError:error)
}