ios - Rss 解析器检查互联网连接并显示一条消息

标签 ios swift nsxmlparser reachability

我正在考虑检查互联网连接并显示一条消息(如果这里没有连接),所以现在我有一个 TableView,我想我必须删除或替换此 TableView 或仅显示一个单元格并显示一条消息就像“没有互联网连接”,所以首先我添加了一个文件来检查连接,所以我这样做了:

    override func viewDidLoad()
    {

        super.viewDidLoad()
        self.navigationController?.navigationBar.barTintColor = UIColor(red: 38.0/255.0, green: 51.0/255.0, blue: 85.0/255.0, alpha: 1.0)
        self.navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "Gotham", size: 13)!, NSForegroundColorAttributeName : UIColor.whiteColor()]
        self.title = "ACTUALITÉS"

        if Reachability.isConnectedToNetwork() == true {

        self.beginParsing()

        } else {
            //Here I'm gonna do something and display an image
        }

    }



    @IBAction func menuTapped(sender: AnyObject) {
        print(delegate)
        delegate?.toggleLeftPanel?()
    }

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

    func beginParsing()
    {
        posts = []
        parser = NSXMLParser(contentsOfURL:(NSURL(string:"url..."))!)!
        parser.delegate = self
        parser.parse()

        tableView!.reloadData()
    }

    //XMLParser Methods

    func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String])
    {
        element = elementName
        if (elementName as NSString).isEqualToString("item")
        {
            elements = NSMutableDictionary()
            elements = [:]
            title1 = NSMutableString()
            title1 = ""
            date = NSMutableString()
            date = ""
            dscrptn = NSMutableString()
            dscrptn = ""
            url = NSURL()
            urlString = NSMutableString()
            urlString = ""
        } else {
            title1 = NSMutableString()
            title1 = "No connection"
        }
    }

    func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?)
    {
        if (elementName as NSString).isEqualToString("item") {
            if !title1.isEqual(nil) {
                elements.setObject(title1, forKey: "title")
            }
            if !date.isEqual(nil) {
                elements.setObject(date, forKey: "date")
            }
            if !dscrptn.isEqual(nil) {
                elements.setObject(dscrptn, forKey: "dscrptn")
            }
            if !urlString.isEqual(nil) {
                elements.setObject(urlString, forKey: "urlString")
            }

            posts.addObject(elements)
        }
    }

    func parser(parser: NSXMLParser, foundCharacters string: String)
    {
        if element.isEqualToString("title") {
            title1.appendString(string)
        } else if element.isEqualToString("pubDate") {
            date.appendString(string)
        } else if element.isEqualToString("description") {
            dscrptn.appendString(string)
        } else if element.isEqualToString("link") {
            urlString.appendString(string)
        }
    }

    //Tableview Methods

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return posts.count
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        let trimUrl = posts.objectAtIndex(indexPath.row).valueForKey("urlString") as! String

        UIApplication.sharedApplication().openURL(NSURL(string: trimUrl.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()))!)
    }

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }

    func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 10
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        return basicCellAtIndexPath(indexPath)
    }


    func basicCellAtIndexPath(indexPath:NSIndexPath) -> ActuTblCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! ActuTblCell

        setTitleForCell(cell, indexPath: indexPath)
        setDateForCell(cell, indexPath: indexPath)
        setDescriptionForCell(cell, indexPath: indexPath)
        return cell
    }

    func setTitleForCell(cell:ActuTblCell, indexPath:NSIndexPath) {
        cell.titleActuCell?.text = posts.objectAtIndex(indexPath.row).valueForKey("title") as! NSString as String
    }

    func setDateForCell(cell:ActuTblCell, indexPath:NSIndexPath) {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
        let dateString = posts.objectAtIndex(indexPath.row).valueForKey("date") as! NSString as String
        if let dateAdded = dateFormatter.dateFromString(dateString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()))
        {
            dateFormatter.dateFormat = "dd/MM/yyyy"
            cell.dateActuCell?.text = "\(dateFormatter.stringFromDate(dateAdded))"
        }
        //cell.dateActuCell?.text = posts.objectAtIndex(indexPath.row).valueForKey("date") as! NSString as String
    }

    func setDescriptionForCell(cell:ActuTblCell, indexPath:NSIndexPath) {
        cell.descriptionActuCell?.text = (posts.objectAtIndex(indexPath.row).valueForKey("dscrptn") as! NSString as String).stripHTML()
    }
}

let     htmlReplaceString   :   String  =   "<[^>]+>"

extension NSString {
    func stripHTML() -> NSString {
        return self.stringByReplacingOccurrencesOfString(htmlReplaceString, withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range: NSRange(location: 0,length: self.length)) as NSString
    }
}


extension String {
    func stripHTML() -> String {
        return self.stringByReplacingOccurrencesOfString(htmlReplaceString, withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range: nil)
    }
}

我知道如何检查连接,但在这里我不知道什么是更好的解决方案以及如何做到这一点。

最佳答案

你想要实现的目标称为空状态。可以找到空状态的想法 www.pttrns.com 。在您的情况下,当没有网络连接时会显示空状态。另一种情况可能是网络连接可用,但解析内容 (XML/JSON) 后 post 数组的项目为零。

我建议您使用第 3 方代码:

另一种方法是为 tableView 设置背景图像。我想注意背景图像的大小应与设备屏幕相同。你可以这样做:

let tempImageView = UIImageView(image: UIImage(named: "yourImage"))
tempImageView.frame = self.tableView.frame
self.tableView.backgroundView = tempImageView;

关于ios - Rss 解析器检查互联网连接并显示一条消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36149400/

相关文章:

iphone - 限制 ASIHTTPRequest 字符串

ios - 如何给 barbuttonitem Action ?

iOS URL 请求。信号量问题

ios - Swift 3 十进制、NSDecimal 和 NSDecimalNumber

swift - 核心数据插入具有多个关系的一对多

ios - 使用 NSXMLParser 根据属性解析 XML

iphone - nsxml解析器问题

ios - iphone - 撤消或反转 kCATransitionPush 以将图像发送到屏幕外

ios - Firebase 的 token 问题

ios - AVFoundation- 相机切换一次,且仅一次