作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我尝试获取有关 url 位于数组中的远程文件的 header 信息。我的获取 header 的函数在单独调用时可以完美运行,但在数组枚举内部时则无法运行。这是我的功能:
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”代码,并在函数“downLoadPic”中返回好的值?
感谢您的回答...
最佳答案
由于 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)
}
}
})
}
关于swift - 枚举数组时获取 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51568740/
我是一名优秀的程序员,十分优秀!