我正在尝试使用以下代码从网站上获取价值,当我在手机上通过WiFi测试手机上的应用程序时,它工作正常,但是当我使用蜂窝数据时,该应用程序崩溃并显示错误array index out of range
经过一些调试之后,调用componentsSeparatedByString
似乎可以通过WiFi进行操作,但不能通过蜂窝数据进行操作(它不会按原样创建阵列)
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.
}
}
最佳答案
您正在做的是web scraping,它固有地不稳定,尤其是您的执行方式。无法保证从该url返回的内容将与您用来拆分html的精确文本匹配。您已经发现根据连接类型会得到不同的响应。如果他们重新设置页面样式怎么办?
转到使用已发布的API的服务,或者在解析时更加自由(但不要use regex)