Swift NSURLSession App在蜂窝数据上崩溃

时间:2014-11-23 19:39:28

标签: ios xcode swift nsurl nsurlsession

我正在尝试使用以下代码从网站获取值,当我在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.
}

}

1 个答案:

答案 0 :(得分:1)

你正在做的是web scraping,这本身就是不稳定的,特别是你做这件事的方式。无法保证从该网址返回的内容与您用于分解html的精确文本相匹配。您已经发现根据连接类型获得不同的响应。如果他们重新设置页面怎么办?

转移到具有已发布API的服务,或者在解析时更加自由(但不要use regex