更改URLSession回调中的变量

时间:2017-12-10 17:46:15

标签: swift nsurlsession

我想检查文件是否存在,然后更改变量的上下文。 如果我在游乐场工作,它会工作,但在视口中编码,没有任何反应。 我使用状态代码检查名为“nameoffile.xml”的文件是否存在,然后var颜色需要更改为“蓝色”。 您将在下面找到我的(不工作)代码。

let url = URL(string: "http://myurl/nameoffile.xml")!
var color = ""

func checkFile()
{
    let req = NSMutableURLRequest(url: url)
    req.httpMethod = "HEAD"
    req.timeoutInterval = 1.0
    var response: URLResponse?
    var task = URLSession.shared.dataTask(with: url) {(data, response, error) in
        if let httpStatus = response as? HTTPURLResponse
        { if httpStatus.statusCode == 200 {
            self.kleur = "blue"
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

从您的示例中,并不完全清楚颜色和网址是否是您调用checkFile的类的属性。我会假设它们是,因为它最有意义。

因此,如果您要更改的颜色是UIView.backgroundColor的属性,并且您希望立即看到更改,则需要在主线程上更改它:

// Your view controller you are using for the task
class MyViewController: UIViewController {
    // The ui element you want to change the colour of
    // If you are using a storyboard you would have a @IBOutlet here
    let button = UIButton()

    func checkFile() {
        // I've noticed you aren't using the NSMutableURLRequest anywhere
        // Also I've cleaned up your code a bit, hope you don't mind
        URLSession.shared.dataTask(with: url) { data, response, error in
            guard let httpStatus = response as? HTTPURLResponse else {
                return
            }
            if httpStatus.statusCode == 200 {
                DispatchQueue.main.async {
                    // This line of code will change the color
                    self.button.backgroundColor = .blue
                }
            }
        }
    }
}

希望这会有所帮助。如果我没有猜到你的问题,请随时改变你的问题或发表评论。