0
我想從下面的代碼網站獲得一個價值崩潰,它工作正常,當我測試應用程序在我的手機上無線網絡,但是當我在蜂窩數據,應用程序崩潰,錯誤array index out of range
做一些調試後,它看起來像調用componentsSeparatedByString
作品通過WiFi而不是通過蜂窩數據(它不創建數組,因爲它應該)斯威夫特NSURLSession應用在蜂窩數據
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.
}
}
jrturton是正確的,網絡刮是不可預知特別是在較慢的連接。然而,你可以處理NULL回報,這是造成你的崩潰使用[NSNull空] – 2015-05-01 15:50:50