2015-11-16 104 views
0

我無法將輸出發佈到標籤。我不得不將它轉換爲字符串?它似乎給我的錯誤是:「不能用類型'Int'的索引來標記類型JiNode的值?」請幫助!Swift HTML解析器

var meter = "" 

@IBAction func calculate(sender: AnyObject) { 
    print("start scraping...") 

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { 

     let url = NSURL(string: "http://uberestimate.com/costs.php") 
     let jiDoc = Ji(htmlURL: url!) 


     if jiDoc != nil { 
      print("html retrived.\n") 
      self.scrapeHTML(jiDoc!) 
     } 
    } 

} 
@IBOutlet weak var resultLabel: UILabel! 
@IBOutlet weak var endingPoint: UITextField! 
@IBOutlet weak var startingpoint: UITextField! 
override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 

} 
override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

private func scrapeHTML(jiDoc: Ji) { 
    println("parsing...\n") 
    let bodyNode = jiDoc.xPath("//body")!.first! 

    var contentDivNode = bodyNode.xPath("//span[@style='font-size:1.3em']").first 

    if contentDivNode == nil { 
     print("unexpected format!") 

    }else{ 
     var cdnArray = contentDivNode[1] 

     var cdn = cdnArray[0]! as String 

     self.resultLabel.text = cdn 

     // println(contentDivNode) 
    } 
return 

} 

}

+0

你應該分享你正在處理的HTML和你得到的錯誤,以讓其他人明白你的問題 – cezheng

+0

它正在顯示HTML,但它沒有顯示在標籤上。當我嘗試將節點轉換爲字符串時,問題就出現了。然後將'字符串'轉換爲'字符串'。我很困惑如何做到這一點。謝謝你var cdnArray = contentDivNode [1] var cdn = cdnArray [0]! as String self.resultLabel.text = cdn –

+0

這是鏈接到第三方庫https://github.com/honghaoz/Ji –

回答

0

你可以這樣做:

@IBAction func calculate(sender: AnyObject) { 
    print("start scraping...") 

    let url = NSURL(string: "http://uberestimate.com/costs.php") 

    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { data, response, error in 
     if data == nil || error != nil { // in Swift 2, I'd use `guard`, but I tried to keep this backward compatible 
      print(error) 
      return 
     } 

     dispatch_async(dispatch_get_main_queue()) { 
      self.scrapeHTML(data!) 
     } 
    } 
    task.resume() 
} 

private func scrapeHTML(data: NSData) { 
    print("parsing...\n") 

    let jiDoc = Ji(data: data, isXML: false) 

    if let contentDivNode = jiDoc?.xPath("//span[@style='font-size:1.3em']")?.first { 
     self.resultLabel.text = contentDivNode.content 
    } 
} 

我使用的是雨燕2.1(和我從println存在,你必須使用較早版本的推斷) ,但我認爲這與Swift版本無關。請注意,我正在將標籤的更新發送回主隊列(因爲您從全局隊列中調用scrapeHTML,但UI更新必須在主線程上發生)。我還使用NSURLSession而不是將同步網絡請求分派給全局隊列。

+0

這是行得通的!它是一個鼓舞人心的。我只是一個初學者,它有助於瞭解像你這樣的資源。謝謝。我會通過我的知識! –