0
@IBOutlet var cityField: UITextField!
@IBOutlet var message: UILabel!

@IBAction func buttonPressed(sender: AnyObject) {

   self.view.endEditing(true)       
   var urlString = "http://www.weather-forecast.com/locations/" + cityField.text.stringByReplacingOccurrencesOfString(" ", withString: "") + "/forecasts/latest"

    var url = NSURL(string: urlString)        
    let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, respons, error) in         
        var urlContent =  NSString(data: data, encoding: NSUTF8StringEncoding)            
        var contentArray = urlContent.componentsSeparatedByString("<span class=\"phrase\">")            
        var newContentArray = contentArray[1].componentsSeparatedByString("</span>")

        self.message.text = newContentArray[0] as? String            
        println(urlString)
    }        
    task.resume()        
}

Here is a simple weather app i'm making, my problem is when i click the button it doesn't really show the weather and it gives me this error "fatal error: Array index out of range" Help, please.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
Abdou23
  • 363
  • 1
  • 4
  • 11

1 Answers1

2

In this line:

    var newContentArray = contentArray[1].componentsSeparatedByString("</span>")

You assume that contentArray will have at least two elements. If it doesn't, you will crash. Obviously that assumption is not correct. You cannot rely on data you receive from outside you app; you must validate that it's in the format you expect before processing it.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • i got that from the page source, do i need to double check that again ? – Abdou23 Sep 12 '14 at 13:04
  • You cannot guarantee the format of a page you fetch from the network. Especially if you're parsing HTML, they could change at any time (it's not even an API). It is not acceptable behavior to crash just because a website sent you data you didn't expect. – Rob Napier Sep 12 '14 at 13:07
  • I know that i have to use an API if i'm going to make a useful reliable app, i was just experimenting with this one, and i thought the problem maws with the syntaxes itself. It works fine now after some changes, but results take too long to show on both simulator and my phone, but shows instantly in console. – Abdou23 Sep 12 '14 at 13:13
  • Even when you're using an API, you need to check that you get back what you expected. Your app should be willing to accept total garbage from the server without crashing. – Rob Napier Sep 12 '14 at 13:25
  • Good tip, thnx for your help Rob. – Abdou23 Sep 12 '14 at 14:03