ios - 如何使用 Json (Swift 2) 将错误处理添加到工作 TableView Controller

标签 ios json swift

我刚刚开始使用 Xcode 7/Swift 2.0 编写应用程序 我的想法已经很成熟了,但我似乎无法让错误处理发挥作用。 它涉及的 View Controller 正在显示我们乐队演奏的日期和时间。

在这个 View Controller 中,我从我们的在线服务器调用 Json 数据并将其解析为 TableView 。这一切都有效。但我也希望发生以下事情。

  1. 如果没有任何连接(wifi/4G/3G),则执行 segue(无连接)
  2. 如果服务器或 php 脚本无法访问,请执行 segue(服务器错误 )
  3. 如果没有可用数据(如空数组),只需给出消息“没有设置日期。”

我从 PHP 脚本中获取的 Json:

(
        {
        date = "some date";
        description = "Some description";
        location = "Some location";
        others = "some details";
        showtime = "some time";
    },
        {
        date = "some date";
        description = "Some description";
        location = "Some location";
        others = "some details";
        showtime = "some time";
    }
)

这是 View Controller

import UIKit

class GigsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    var gigsdata: NSArray = []

    override func viewDidLoad() {
        super.viewDidLoad()

        let logo = UIImage(named: "where_is_header_navigationController.jpg")
        let imageView = UIImageView(image:logo)
        self.navigationItem.titleView = imageView

        func dataOfJson(url: String) -> NSArray {
            let gigsdata = NSData(contentsOfURL: NSURL(string: url)!)
            let jsonArray: NSArray = try! NSJSONSerialization.JSONObjectWithData(gigsdata!, options: .MutableContainers) as! NSArray
            return jsonArray
        }
        gigsdata = dataOfJson("http://www.mydomain.eu/app/myscript.php")

    }// end of viewDidLoad

    // MARK: Table View Delegate Methods
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if gigsdata.count != 0 {
            return gigsdata.count

        } else {

            return 1
        }

    }

    func allowMultipleLines(tableViewCell:UITableViewCell) {
        tableViewCell.textLabel?.numberOfLines = 0
        tableViewCell.textLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("GigsCell")! as UITableViewCell
        // setting the text color
        cell.textLabel?.textColor = UIColor.whiteColor()
        //Getting the JSON data and turn it into objects
        let maingigsdata = (gigsdata[indexPath.row] as! NSDictionary)
        //setting constants for the detailview
        let gigsDate = maingigsdata["date"] as! String
        let gigsLocation = maingigsdata["location"] as! String
        // Setting the number of lines per row
        cell.textLabel!.numberOfLines = 2
        // Filling the cell with data
        cell.textLabel!.text = ("\(gigsDate) \n\(gigsLocation)")
        // setting the beackground color when selected
        let backgroundView = UIView()
        backgroundView.backgroundColor = UIColor.darkGrayColor()
        cell.selectedBackgroundView = backgroundView

        return cell
    }


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


}

就像我说的,我对此还很陌生,所以请不要到处命名各种过程、函数或类似的东西。 请不要以为我自己不尝试,但现在已经被困了两周了。

我在视频和教程中看到的很多内容都是“DO TRY CATCH”。 但尽我所能地实现这一点却给了我各种各样的错误,所以我一定是在那里做错了什么。

我希望有人可以帮助我,让我变得像今天一样聪明!

最佳答案

您应该使用 NSURLRequest 或像 Alamofire 这样的库来获取数据。 NSData contentOfURL 不是异步的,在您的情况下会阻塞主线程。我想知道您是否可以将代码编译为 NSData contentOfURL 抛出和必须捕获的异常。检查抛出的 NSError 对象的域。它可以是例如NSURLErrorDNSLookupFailed、NSURLErrorDomain、NSURLErrorNotConnectedToInternet、NSURLErrorInternationalRoamingOff。

https://github.com/Alamofire/Alamofire

要取消连接类型:

Detect carrier connection type (3G / EDGE / GPRS)

基于您的代码的错误处理示例:

do {
    // Blocks your UI if you do this in the main thread!
    let gigsdata = NSData(contentsOfURL: NSURL(string: url)!)
}
catch let error as! NSError {
    if error.domain == NSURLErrorNotConnectedToInternet {
        // If you do the data fetch using the background queue then this must be dispatched to the main queue:
        performSegueWithIdentifier("noInternet", sender: self)
    }
}

关于ios - 如何使用 Json (Swift 2) 将错误处理添加到工作 TableView Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35258767/

相关文章:

ios - 如何在 swift iOS 中编写正确的目标选择器?

当我只想要父对象时,JSONPath 查询从嵌套对象返回同名键

php - 如何创建从 nodejs mysql 模块获取的正确的 json 类型数据?

java - Log4J - JsonLayout 和 RollingFileAppender 生成无效的 JSON

swift - 连接 Swift 自定义键盘中的按钮时出错

swift - TestFlight 未收到通知

Swift:如何将数据添加到对象列表中对象的变量中

ios - 使用 UINavigationController 工具栏的替代方法

android - Ionic 4 加载本地资源不适用于 IOS

ios - 无法本地化我的应用程序(添加本地化语言显示没有文件,也没有添加任何内容)