gpt4 book ai didi

swift - 枚举数组时获取 header

转载 作者:行者123 更新时间:2023-11-30 11:18:09 27 4
gpt4 key购买 nike

我尝试获取有关 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com