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

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

问题描述

我正在学习 Swift,但我在 ViewDidLoad 中有一个 Int 类型的变量(跟随者),我将该值设置为默认值 0 .然后我执行一个返回 1 数组的 Json 请求,并将 Followers 的值设置为 Json 数组内的任何数字,即 788 .但是,当我之后执行 Print 时,该值保持为 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) 

          }

如您所见,follower 变量设置为 0 当我执行 HttpPost 时,我可以看到当我有 print(self.followers) 时,变量设置为 788,但除此之外当我访问变量时循环它的值回到 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.

您应该将处理响应的代码放在完成处理程序中.即使你的 The value here say 0 打印语句发生在你调用网络任务上的 resume 之后,数据还没有被检索到.

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!
}

视图控制器有一个名为 handledDownloadButton() 的 IBAction 函数.那个函数:

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

  • 禁用下载按钮并显示活动指示器视图.
  • 调用下载管理器的 downloadFileAtURL() 来下载文件,并传入一个完成处理程序.完成处理程序会进行大量的错误检查.如果一切顺利,它会将结果数据转换为 UIImage 并将其安装在图像视图中,然后调用对图像执行一些动画的方法,然后丢弃图像并重新启用下载按钮.

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

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