Check content type when file is done downloading nsurlsessiondownloadtask

时间:2015-09-30 23:16:05

标签: ios swift nsurlsession

I am using a nsurlsession to manage downloading image/video files. Trouble is sometimes the request goes bad and returns text like "Content not found." How can I make sure that the file thats being downloaded is actually the file type I requested? (such as .jpeg or .mp4)

2 个答案:

答案 0 :(得分:1)

您可以检查内部URLSession方法didReceiveResponse响应属性MIMEType并检查它是否是" image / jpg":

func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
    if response.MIMEType == "image/jpg" || response.MIMEType == "image/jpeg" {
        completionHandler(NSURLSessionResponseDisposition.BecomeDownload)
    } else {
        // your code when it is not jpeg
    }
}

答案 1 :(得分:0)

快速版本

guard let httpUrlResponse = sessionTask.response as? HTTPURLResponse else {
    return
    
}
guard let mimeType = httpUrlResponse.mimeType else {
    return
}
相关问题