将 URL 数据保存到变量 [英] Saving URL data to a variable

查看:48
本文介绍了将 URL 数据保存到变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图从 RESTful API 获取一个简单的数据字符串.下面是响应的样子:

So I am trying to get a simple string of data back from a RESTful API. Here is what a response looks like:

Hello

它不是以 XML 或 JSON 格式或任何只是简单字符串的格式,因为一次只传回一个单词.所以这就是我的 swift 的样子:

It is not formatted in XML or JSON or anything just a simple string because only one word is being passed back at a time. So here is what my swift looks like:

let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in

    if error != nil {
        println("error: \(error.localizedDescription): \(error.userInfo)")
    }
    
    var withNewLine:NSString = NSString(data: data, encoding: NSUTF8StringEncoding)!
    let str:NSString = withNewLine.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

    dispatch_async(dispatch_get_main_queue(), {
        self.spellCorrection = str
    })
})

task.resume()

我在str"中得到了正确的数据在我进入 dispatch_async() 方法之前的变量.但是当我进入 dispatch_async() 方法时,str"变量变为 nil,我不知道为什么.我只是想将单个单词保存在我班级中的一个变量中,所以如果我完全错误地解决这个问题,请告诉我.我真的很感激我能得到的任何帮助.谢谢!

I get the correct data back in the "str" variable before I go into the dispatch_async() method. But when I do go into the dispatch_async() method the "str" variable becomes nil and I am not sure why. I am just trying to save the single word in a variable within my class, so if I am going about this completely wrong let me know. I would really appreciate any help I can get. Thanks!

好的,所以我应该在我第一次发布时就包含这个.我也试过这个:

Okay so I should have included this the first time I posted. I have also tried this:

let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in

    if error != nil {
        println("error: \(error.localizedDescription): \(error.userInfo)")
    }
    
    var withNewLine:NSString = NSString(data: data, encoding: NSUTF8StringEncoding)!
    self.spellCorrection = withNewLine.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
})

task.resume()

但是当我这样做时,completionHandler 完成后,字符串不会留在 self.spellCorrection 变量中.所以我的问题是,我应该怎么做才能在完成处理程序完成后将字符串保留在 self.spellCorrection 变量中?谢谢!

But when I do this the string does not stay in the self.spellCorrection variable after the completionHandler has finished. So my question is, what should I do to keep the string in the self.spellCorrection variable after the completionHandler has finished? Thanks!

在 viewDidLoad 中:

In viewDidLoad:

var spellCorrection: NSString = ""
//First print
println(self.spellCorrection)

在我稍后调用的方法中,我有:

In the method I call later I have:

func spellCheck() {
    var check: String = "http://theURL.com/?text=" + condenseWhitespace(self.lastTypedWord)
    let url = NSURL(string: check)
    let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
        
        if error != nil {
            println("error: \(error.localizedDescription): \(error.userInfo)")
        }
        
        var withNewLine:NSString = NSString(data: data, encoding: NSUTF8StringEncoding)!
        self.spellCorrection = withNewLine.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    }).resume()
    //Print after the completionHandler
    println(self.spellCorrection)
}

推荐答案

您在答案的更多详细信息"部分下添加的代码中很清楚,即

As is clear in the code you've added under the "More Details" section of your answer, i.e.

let task: Void = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in

   // ...

   self.spellCorrection =    withNewLine.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNew lineCharacterSet())
   println(spellCorrection)
}).resume()

println(self.spellCorrection)

通过直接在块外部打印 self.spellCorrection,您试图在异步 dataTaskWithURL 块中设置它之前打印它.

by printing self.spellCorrection directly outside of the block, you're attempting to print it before it's been set in the async dataTaskWithURL block.

异步块在后台执行,因此在您的块在主线程上执行后立即编写的代码,异步块中的代码尚未完成.这就是 self.spellCorrection 在 async 块内正确打印的原因——因为在这一点上,代码肯定已经执行了;但是你不能像你所做的那样直接在异步块之外打印更新的值,因为异步代码还没有完成执行.

An async block performs in the background, so as the code written immediately after your block executes on the main thread, the code within the async block will not yet be complete. That's why self.spellCorrection prints correctly inside the async block -- because at that point, the code has definitely executed; but you cannot print the updated value directly outside of the async block as you've done, because the async code hasn't finished executing yet.

所以,是的,您的 self.spellCorrection 实际上已正确设置,但您必须等到异步代码执行后才能检查新值.检查更新值的可靠方法实际上是在异步块中打印它.

So, yes, your self.spellCorrection has in fact been set correctly, but you have to wait until after the async code executes before checking for the new value. And the surefire way to check for that updated value is in fact by printing it within the async block.

这篇关于将 URL 数据保存到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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