简体   繁体   中英

The downloaded file, MP3 File, is damaged through NSURL Session in Swift

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)


}

have you tried Alamofire? I would highly recommend using this pod for any HTTP requests / downloads. Example: Alamofire.download() method: Where is the file and did it save successfully?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM