2017-12-10 4 views
-2

ファイルが存在するかどうかを確認してから、変数のコンテキストを変更します。 私は遊び場で働いていても動作しますが、ビューポートでコーディングすると何も起こりません。 ステータスコードを使用して "nameoffile.xml"というファイルが存在するかどうかを確認してから、var色を "blue"に変更する必要があります。 以下は私の(動作していない)コードです。URLSessionコールバック内の変数を変更します。

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

あなたの例では、 ''青色 ''に '' kleur'属性を割り当てていますが、コードの先頭に ''色付けされています。これをSOに書き直している間に現れたのは単なるエラーですか? –

+0

「機能しない」とはどういう意味ですか? –

答えて

0

あなたの例では、colorとurlが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 
       } 
      } 
     } 
    } 
} 

は、この情報がお役に立てば幸いです。あなたの問題を推測していない場合は、質問を変更したりコメントを残してください。

関連する問題