gpt4 book ai didi

ios - Swift NSURLSession App 在蜂窝数据上崩溃

转载 作者:行者123 更新时间:2023-11-29 02:29:25 24 4
gpt4 key购买 nike

我正在尝试使用以下代码从网站获取值,当我在手机上通过 WiFi 测试应用程序时,它工作正常,但当我使用蜂窝数据时,应用程序崩溃并出现错误 array index out范围经过一些调试后,看起来调用 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)

关于ios - Swift NSURLSession App 在蜂窝数据上崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27093417/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com