function with dataTask returning a value

前端 未结 4 1213
深忆病人
深忆病人 2020-12-06 14:26

I wan\'t to check if my url statusCode equals to 200, I created a function returning a Boolean if the statusCode equals to 200, I\'m using a dataTask, but I don\'t know how

4条回答
  •  被撕碎了的回忆
    2020-12-06 14:46

    Consider semaphore if you want to keep your original return pattern.

    func checkUrl(urlString: String) -> Bool {
        if let url = URL(string: fileUrl) {
            var result: Bool!
    
            let semaphore = DispatchSemaphore(value: 0)  //1. create a counting semaphore
    
            let session = URLSession.shared
            session.dataTask(with: url, completionHandler: { (data, response, error) in
                result = true  //or false in case
                semaphore.signal()  //3. count it up
            }).resume()
    
            semaphore.wait()  //2. wait for finished counting
    
            return result
        }
    
        return false
    }
    

提交回复
热议问题