I am trying to get a value from a website with the following code, it works fine when I test the app on my phone on WiFi but when I am on cellular data, the app crashes with error array index out of range
After doing some debugging, it looks like calling componentsSeparatedByString
works over WiFi but not over cellular data (it does not create the array as it should)
import UIKit
import Foundation
class ViewController: UIViewController {
@IBOutlet weak var goldPriceLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var urlString = "http://www.cookson-clal.com/cours/"
var url = NSURL(string: urlString)
var defaultConfigObject = NSURLSessionConfiguration.defaultSessionConfiguration()
defaultConfigObject.allowsCellularAccess = true
var session = NSURLSession(configuration: defaultConfigObject)
let task = session.dataTaskWithURL(url!) {(data, response, error) in
var pageCode = NSString(data: data, encoding:NSUTF8StringEncoding)!
var contentArray = pageCode.componentsSeparatedByString("<td width=\"16%\" align=\"right\" class=\"indx_4\">")
var newContentArray = contentArray[1].componentsSeparatedByString("</td>")
var goldPriceString = (newContentArray[0].stringByReplacingOccurrencesOfString("€", withString: "").stringByReplacingOccurrencesOfString(",", withString: "."))
var ASCIIgoldPrice = String()
for tempChar in goldPriceString.unicodeScalars {
if (tempChar.isASCII()) {
ASCIIgoldPrice.append(tempChar)
}
}
var goldPrice:Float = (ASCIIgoldPrice as NSString).floatValue
dispatch_async(dispatch_get_main_queue()) {
self.goldPriceLabel.text = "\(goldPrice)"
}
println(goldPrice)
}
task.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
What you're doing is web scraping which is inherently unstable, particularly the way you're doing it. There is no guarantee that the content returned from that url will match up with the precise text you're using to break up the html. You've already found that you get different responses depending on the connection type. What if they restyle the page?
Move to a service with a published API, or be a bit more liberal with your parsing (but don't use regex)