枚举数组时获取标头

时间:2018-07-28 06:34:30

标签: swift macos

我尝试获取有关位于数组中的url的远程文件的标头信息。 我的获取标头的函数在单独调用时可以完美工作,但在数组枚举内部时则不能。 这是我的功能:

    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”内部返回良好的值?

感谢您的回答...

1 个答案:

答案 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)
            }
       }
    })
}
相关问题