swift - 当dispatch_async(dispatch_get_main_queue())运行时如何从类方法发送信息

标签 swift swift2

我有一个 ViewController,点击按钮后我想从网络获取数据。

let myClass = Class()
    myClass.myMethod() {
        dispatch_async(dispatch_get_main_queue()) {               
        }
    }

在我的类文件中我有一个方法

func myMethod( completion:()->() ) {  
    if let connectToInternetAndGetDataFromWeb
        completion()
    } else {
        print("Cold not construct a valid URL")
        completion()
    }
}

我的类(class)是连接到互联网并获取数据

func downloadJSONFromURL() {
    if let httpResponse {
        switch(httpResponse.statusCode) {
        case 200:
        // 2. Create JSON Object with data
            do { 
                try 
            } catch {
                print(error)
            }
        }             
    } else {
        print("Error: Not a valid HTTP response")            
    }   
    dataTask!.resume()
}

我的问题是如何将反馈发送到 ViewController 以显示来自类的警报信息。如果我有互联网连接就可以,但例如当我提供错误的网址时,我会出现错误 print("Error: Not a valid HTTP response") 但我如何将此错误发送到 ViewController ?

最佳答案

有多种方法可以做到这一点。 我认为您的情况最简单的部分是在 downloadJSONFromURL() 中添加一个闭包参数。

func downloadJSONFromURL(completion:((error:NSError?)->Void)) {
    if let httpResponse {
        switch(httpResponse.statusCode) {
        case 200:
        // 2. Create JSON Object with data
            do { 
                try 
                completion(nil)
            } catch {
                print(error)
                completion(error)
            }
        }             
    } else {
        print("Error: Not a valid HTTP response")            
    }   
    dataTask!.resume()
}

当然,您必须将完成闭包链接到发出请求的 UIViewController 。因此,myMethod还在它的闭包中获取一个可选的错误参数,等等。 最后你有像这样的 UIViewController 类

let myClass = Class()
    myClass.myMethod() {(error:NSError?) -> Void in
        dispatch_async(dispatch_get_main_queue()) { 
          //Show Alert or whatever is necessary for the error
        }
    }

关于swift - 当dispatch_async(dispatch_get_main_queue())运行时如何从类方法发送信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32020312/

相关文章:

ios - 在对角处添加两个标签

ios - 如何将 tableview 单元格附件应用于 tableview 记录

ios - "unrecognized selector sent to instance error"当首先编辑地址字段然后返回日期时间选择器时

ios - 无法从 firebase 数据库获取 key

ios - 什么是 objc_AssociationPolicy?它是如何工作的?

swift - 我如何确定一个正方形是否可以在不与其他 Sprite 接触的情况下到达位置?

arrays - 检查哪个日期最接近今天

ios - 检查存储的文件和通过 URL 访问的文件之间的区别

swift - Swift 中的隐式惰性静态成员

ios - Swift stringByRemovingPercentEncoding 问题与重音字符像ë