func getHeaderInformations (myUrl: URL, completion: @escaping (_ content: String?) -> ()) {
var request = URLRequest(url: myUrl)
request.httpMethod = "HEAD"
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard error == nil, let reponse = response as? HTTPURLResponse, let contentType = reponse.allHeaderFields["Content-Type"],let contentLength = reponse.allHeaderFields["Content-Length"]
else{
completion(nil)
return
}
let content = String(describing: contentType) + "/" + String(describing: contentLength)
completion(content)
}
task.resume()
}
// download picture
func downloadPic (){
let minimumSize=UserDefaults.standard.object(forKey: "Minimum_size") as! Int64
var imgExtension:String=""
var type:String=""
var size:Int64=0
for (_,item) in LiensImgArrayURL.enumerated() {
getHeaderInformations(myUrl: item, completion: { content in
let myInfoArray = content?.components(separatedBy: "/")
type=(myInfoArray?[0])!
imgExtension=(myInfoArray?[1])!
size=Int64((myInfoArray?[2])!)!
})
if (type=="image" && size>=minimumSize) {
SaveFileToDirectory(myRemoteUrl: item, myExtension: imgExtension)
}
}
}
我如何才能很好地为“ getHeaderInformations”编写此代码,并在func“ downLoadPic”内部返回良好的值?
感谢您的回答...
答案 0 :(得分:0)
由于getHeaderInformations
异步工作,因此将代码保存文件到中。
如果您不需要for
循环中的索引,则也不需要enumerated()
。
我调整了代码位以摆脱难看的问题,感叹号和括号。
for item in LiensImgArrayURL {
getHeaderInformations(myUrl: item, completion: { content in
if let myInfoArray = content?.components(separatedBy: "/") {
type = myInfoArray[0]
imgExtension = myInfoArray[1]
size = Int64(myInfoArray[2])!
if type == "image" && size >= minimumSize {
SaveFileToDirectory(myRemoteUrl: item, myExtension: imgExtension)
}
}
})
}