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.
}
}