下载的文件MP3文件在Swift

时间:2016-10-29 07:36:24

标签: swift download mp3 nsurlsession

我尝试使用swift下载iPhone中的mp3文件。但那些文件有时会损坏。 (由于此问题,下载的Mp3的持续时间发生了变化。因此无法在MPmovieplayer中读取正确的持续时间)我不知道为什么。你能帮我解决问题吗?

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)


}

1 个答案:

答案 0 :(得分:0)

你试过Alamofire吗?我强烈建议您使用此pod进行任何HTTP请求/下载。 例: Alamofire.download() method: Where is the file and did it save successfully?