The label does not change.

Asked 2 years ago, Updated 2 years ago, 31 views

import UIKit

classViewController:UIViewController {

    @IBOutletweakvarcityTextField:UITextField!


    @IBOutlet weak var resultLabel:UILabel!
    @ IBAction func findWeather (sender: AnyObject) {

        var wasSuccessful=false

        let attemptedUrl = NSURL (string: "http://www.weather-forecast.com/locations/" + cityTextField.text!.stringByReplacingOccurrencesOfString(", withString: "-") + "/foreecasts/latest")!

        if let url:NSURL=attemptedUrl{

        let task = NSURLSession.sharedSession().dataTaskWithURL(url){(data, response, error)->Void in

            iflet urlContent=data{

                letwebContent=NSString(data:urlContent, encoding:NSUTF8StringEncoding)

                let websiteArray=webContent?.componentsSeparatedByString("3Day Weather Forecast Summary:</b><span class=\"read-more-small\">span class=\"read-more-content\">span class=\"read-more-content\">span class>" &"read-more-content\">span class"

                if websiteArray!.count>1 {

                    let weatherArray=websiteArray![1].componentsSeparatedByString("</span>")

                    if weatherArray.count>1 {

                        wasSuccessful=true

                        let weatherSummary=weatherArray[0].stringByReplaceingOccurrencesOfString("&deg;", withString:" "")

                        dispatch_async(dispatch_get_main_queue(), {()->Void in


                            self.resultLabel.text=weatherSummary
                        })

                    }

                }



            }

            if wasSuccessful==false{

                **self.resultLabel.text="Couldn't find the weather for that city-please try again."**

            }
        }

        task.resume()

        } else{

            **self.resultLabel.text="Couldn't find the weather for that city-please try again."**

        }
    }
    override func viewDidLoad(){
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from anib.


    }

    override funcdidReceiveMemoryWarning(){
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

I am creating a weather forecast application.
** Regarding the field enclosed by **, when you enter something other than the city name, I intend to convert the field enclosed by **** into a label.

However, if you type something other than the city name and press the button, the label does not change.

Where is the problem with the code?

swift

2022-09-29 22:51

1 Answers

Just like when it wasn't an error, use dispatch_async to process it in the main queue.

 if wasSuccessful==false{

    dispatch_async(dispatch_get_main_queue(), {()->Void in
        self.resultLabel.text="Couldn't find the weather for that city-please try again."
    })
}


2022-09-29 22:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.