Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Rest 在Swift中从闭包中获取数据_Rest_Swift_Closures - Fatal编程技术网

Rest 在Swift中从闭包中获取数据

Rest 在Swift中从闭包中获取数据,rest,swift,closures,Rest,Swift,Closures,我正在尝试对var url:String=”进行测试REST调用http://ip.jsontest.com/“使用Swift。我想做的是在UITextView中显示结果(基本上只是打印JSON) 现在我想用这个片段来实现这一点: NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: N

我正在尝试对
var url:String=”进行测试REST调用http://ip.jsontest.com/“
使用Swift。我想做的是在UITextView中显示结果(基本上只是打印JSON)

现在我想用这个片段来实现这一点:

     NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in 
// code

但是,我不知道如何将闭包中的数据获取到UITextView中。打印到控制台没有问题,但将数据写入var并将其返回到我的文本视图是不起作用的。

完成以下关闭操作

编辑:

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) in
if(data != nil){
    //Display the json using your textview object
    //self.textView.text = .... data (convert the data as you wanted.)
    let responseData : NSString = NSString(data: data, encoding: NSUTF8StringEncoding)
    self.textView.text = reponseData


 }
})

基本上我可以这样得到数据:

   dispatch_async(dispatch_get_main_queue())
                {
                    self.resultView.text = "\(data)"

            }

“以NSException类型的未捕获异常终止”,只要我尝试在该闭包内设置textView.text。奇怪,因为我可以轻松打印LN(数据),但设置self.textView.text=“(数据)”会引发异常。请将响应从NSData转换为NSString,然后重试。正如我更新了上面的答案。您还应该确保在主UI线程上设置UITextView.text,方法是将其包装在
dispatch\u async(dispatch\u get\u main\u queue()){…}