2014-11-23 30 views
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. 
} 

} 

回答

1

你在做什麼是web scraping這是內在的不穩定性,尤其是你這樣做的方式。誰也不能保證從該URL返回的內容將匹配與您正在使用打破了HTML的精確文本。你已經發現,你根據連接類型的不同反應。如果他們重新設置頁面呢?

移動到服務與已發佈的API,或者是多一點的自由與解析(但不要use regex

+0

jrturton是正確的,網絡刮是不可預知特別是在較慢的連接。然而,你可以處理NULL回報,這是造成你的崩潰使用[NSNull空] – 2015-05-01 15:50:50