没有保存整数的IOS Swift值 [英] IOS Swift value of an Integer is not being saved

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

问题描述

我正在学习Swift,但我在ViewDidLoad中有一个Int类型的Variable(Followers),我将该值设置为默认值0。然后我做一个返回1个数组的Json Request,并将Followers的值设置为Json数组中788的数字。然而,当我之后进行打印时,值保持为0.这是我的代码,它会更有意义

I am learning Swift but I have a Variable (Followers) of type Int in ViewDidLoad, I set the value to a default of 0 . I then do a Json Request which returns 1 array and I set the value of Followers to whatever number it is inside the Json Array which is 788 . However when I do a Print afterwards the value keeps staying at 0. This is my code and it'll make more sense

 override func viewDidLoad() {
        super.viewDidLoad()
        var followers = 0

     // Sent HTTP Request

        sessionn.dataTask(with:requestt, completionHandler: {(data, response, error) in
            if error != nil {
                //    print(error)
            } else {
                do {

                    let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]
                    if let Profiles = parsedData["data"] as! [AnyObject]? {

                        for Profiles in Profiles {

                            if let follow = Profiles["followers"] as? Int {
                                self.followers =  follow
                              // The value here says 788
                                  print(self.followers)

                            }



                        }
                        DispatchQueue.main.async {

                        }
                    }

                } catch let error as NSError {
                    print(error)
                }

            }

        }).resume()


        print("Followers is")
     // The value here says 0 every time
        print(followers)
       // I have even tried
        print(self.followers) 

          }

正如你所看到的追随者变量被设置为0当我做我的HttpPost时,我可以看到当我有打印(self.followers)时,变量设置为788但是当我访问变量时,对于Loop,它的值会回到0。如何通过构建应用程序来学习Swift,从而纠正错误。

As you can see the followers variable is set to 0 When I do my HttpPost i can see that the Variable is set to 788 when I have print(self.followers) however outside of that for Loop when I access the variable it's value goes back to 0 . How can I correct that mistake as I am learning Swift by building an app.

推荐答案

您误解了异步代码的工作原理。

You misunderstand how async code works.

当您设置 NSSession 数据任务时,调用 task.resume()在网络请求发出之前立即返回。

When you set up an NSSession data task, the call to task.resume() returns immediately, before the network request has been sent out.

您应该将处理响应的代码放在完成处理程序中。即使您的此处的值显示0 在网络任务上调用resume后发生了print语句,但尚未检索到数据。

You should put the code that handles the response INSIDE the completion handler. Even though your The value here says 0 print statement happens after you call resume on the network task, the data has not been retrieved yet.

想象一下,你正在做晚餐,然后你把孩子送去买一袋面粉。你说孩子,给我一些面粉。当你回来的时候按下公寓门上的蜂鸣器,我会把你嗡嗡叫。

Imagine you are cooking dinner and you send your kid out to get a bag of flour. You say "Kid, go get me some flour. Press the buzzer on the apartment door when you're back and I'll buzz you in."

然后你转过身来回到烹饪晚餐的其他部分,但你不要指望你告诉你的孩子去面粉的那一刻,你会低头看着柜台,面粉将在那里。你知道你必须等到蜂鸣器发出嗡嗡声,然后你的孩子才会回来。

You then turn back to cooking the other parts of dinner, but you don't expect that the instant you tell your kid to go get flour, you'll look down on the counter and the flour will be there. You know that you have to wait until the buzzer buzzes, and then your kid will be back with the flour.

提交网络任务就是这样。对 task.resume()的调用类似于您对面粉的请求。您提交请求,但在请求完成处理之前继续执行您正在执行的操作。 完成处理程序正在运行的是蜂鸣器,让您知道您的孩子回来了面粉。

Submitting a network task is like that. The call to task.resume() is similar to your request for flour. You submit the request, but you go on with what you are doing before the request has finished processing. The completion handler running is the buzzer that lets you know your kid is back with the flour.

我在Github上创建了一个项目,演示了如何在URLSession中使用完成处理程序。该项目名为 Async_demo (链接)

I've created a project on Github that demonstrates using a completion handler in URLSession. The project is called Async_demo (link)

关键部分是DownloadManager.swift中的方法 downloadFileAtURL()

The key part is the method downloadFileAtURL() in DownloadManager.swift

注意该函数如何将完成处理程序作为参数。该函数使用完成处理程序创建URLSession数据任务。在完成处理程序内,对于 URLSession 数据任务, downloadFileAtURL()函数调用传递给它的完成处理程序它。它使用 DispatchQueue.main.async()来调用主线程上的完成处理程序。

Note how the function takes completion handler as a parameter. The function creates an URLSession data task with a completion handler. Inside the completion handler, for the URLSession data task, the downloadFileAtURL() function calls the completion handler that was passed to it. It uses DispatchQueue.main.async() to call the completion handler on the main thread.

此演示项目使用 URLSession 数据任务,并明确禁用数据缓存,以便每次单击下载按钮时都会重新加载图像。

This demo project uses an URLSession data task, and explicitly disables data caching, so that the image will be reloaded each time you click the download button.

以下是DownloadManager.swift中 downloadFileAtURL()函数的代码:

Here is the code for the downloadFileAtURL() function in DownloadManager.swift:

func downloadFileAtURL(_ url: URL, completion: @escaping DataClosure) {

  //We create a URLRequest that does not allow caching so you can see the download take place
  let request = URLRequest(url: url,
                           cachePolicy: .reloadIgnoringLocalAndRemoteCacheData,
                           timeoutInterval: 30.0)
  let dataTask = URLSession.shared.dataTask(with: request) {
    data, response, error in

    //Perform the completion handler on the main thread
    DispatchQueue.main.async {
      //Call the copmletion handler that was passed to us
      completion(data, error)
    }
  }
  dataTask.resume()

  //When we get here the data task will NOT have completed yet!
}

视图控制器有一个名为的I​​BAction函数processedDownloadButton( )。该功能:

The view controller has an IBAction function called handledDownloadButton(). That function:


  • 禁用下载按钮并显示活动指示器视图。

  • 调用下载经理的downloadFileAtURL()下载文件,传入一个完成处理程序。完成处理程序执行了大量的错误检查。如果一切正常,它会将结果数据转换为UIImage并将其安装在图像视图中,然后调用在图像上执行某些动画的方法,然后丢弃图像并重新启用下载按钮。

这篇关于没有保存整数的IOS Swift值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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