如何从类内部调用presentViewController [英] How to call presentViewController from inside class

查看:41
本文介绍了如何从类内部调用presentViewController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的完成处理程序中,我试图返回类似于 JS 中的 alert 的 http 响应代码.一旦我得到这个排序,我希望改进我的 if 语句来识别最终用户的连接问题.我正在看这篇文章.

Inside my completion handler I am trying to return the http response code much like alert in JS. Once I get this sorted I hope to improve my if statement to identify a connection problem to the end user. I was looking at this article.

http://www.ioscreator.com/tutorials/display-an-alert-view-in-ios8-with-swift

我也看到了这个答案 Simple App Delegate方法来显示 UIAlertController(在 Swift 中) 但我得到了一个关于 window 没有被命名的类似方法.

I have also seen this answer Simple App Delegate method to show an UIAlertController (in Swift) but I get a similar method about the window not being named.

我没有噪音的代码是这样的:

My code without all the noise is like this:

class NewsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var tableView: UITableView!
var titleItems: NSMutableArray = []
var descritpionItems: NSMutableArray = []

class RemoteAPI {

    // base url
    let baseUrl = "http://api.dev/web/"
    // returned array of news titles + descriptions
    var newsTitle: NSMutableArray = []
    var newsDescription: NSMutableArray = []

    func getData(completionHandler: ((NSArray?, NSError?) -> Void)) -> Void {
        // get news feed url
        let url = NSURL(string: baseUrl + "news")
        // create session
        let session = NSURLSession.sharedSession()
        // set task
        let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in

            // if error isn't nil return error to getData
            if (error != nil) {
                return completionHandler(nil, error)
            }

            // check response
           if let httpResponse = response as? NSHTTPURLResponse {
                // if response doesn't equal 200 throw an alert
                 if httpResponse.statusCode != 200 {
                let alertController = UIAlertController(title: "Oh No!!", message: "Connection error",preferredStyle: UIAlertControllerStyle.Alert)

                alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil))

                UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)

                } else { // no error continue

            // convert data object to json
            let json = JSON(data: data)

            for var i = 0; i < json.count; ++i {
                // get news title from json object
                var title = json[i]["title"].string
                var blurb = json[i]["description"].string
                // add to dictionary
                self.newsTitle.addObject(title!)
                self.newsDescription.addObject(blurb!)
            }

            if (error != nil) {
                return completionHandler(nil, error)
            } else {
                return completionHandler([self.newsTitle,self.newsDescription], nil)
            }
        }
    }
    })
        task.resume()
    }
}

// get data
var api = RemoteAPI()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    self.view.frame = CGRect(x: 5, y: 75, width: 365, height: 480)
    self.tableView = UITableView(frame:self.view!.frame)
    self.tableView!.delegate = self
    self.tableView!.dataSource = self
    self.tableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
    self.view?.addSubview(self.tableView)

    api.getData({data, error -> Void in
        if (data != nil) {
            self.titleItems = self.api.newsTitle
            self.descritpionItems = self.api.newsDescription
            self.tableView!.reloadData()
        } else {
            println("API failed :-(")
            println(error)
        }
    })
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{

    return self.titleItems.count
}

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

    var cell:UITableViewCell=UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "mycell")

    if let newsTitle = self.titleItems[indexPath.row] as? NSString {
        cell.textLabel?.text = newsTitle
    }
    if let newsDesc = self.descritpionItems[indexPath.row] as? NSString {
        cell.detailTextLabel?.text = newsDesc
    }
    return cell
}

}

我收到NewsViewController.RemoteAPI 没有名为presentViewController 的成员的错误.我明白为什么,只是不确定如何在 iOS 新手的类中调用它

I get an error of NewsViewController.RemoteAPI does not have member named presentViewController. I understand why, just not sure how to call this within the class being new to iOS

推荐答案

您的类 RemoteAPI 没有名为 presentViewController() 的方法.presentViewController()UIViewController 上的一个方法.这就是您收到错误的原因.

Your class RemoteAPI does not have a method called presentViewController(). presentViewController() is a method on a UIViewController. This is why you are getting the error.

要调用 presentViewController(),请在 HTTP 响应完成时回调 UIViewController 实例.

To call presentViewController(), call back to a UIViewController instance when your HTTP response finishes.

api.getData()else 块中,您可以访问错误对象.您可以在此处创建警报控制器,然后展示它.此代码块称为回调,您的视图控制器应负责创建指示错误的警报控制器.

Inside your else block of api.getData(), you can access the error object. Here you can create your alert controller and then present it. This block of code is called a callback, and your view controller should be responsible for creating the alert controller that indicates an error.

这篇关于如何从类内部调用presentViewController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆