草庐IT

swift - 如果执行嵌套异步调用,函数运行两次,否则运行一次。需要帮助预先确定何时会发生

coder 2023-09-14 原文

func handleGetAllPhotoURLs 从下面的行调用,我已经确认代码行只执行一次断点。

_ = FlickrClient.getAllPhotoURLs(currentPin: self.currentPin, fetchCount: fetchCount, completion: self.handleGetAllPhotoURLs(pin:urls:error:))

根据我的 print 语句的输出,该函数运行两次,因为如果 urls.count 不为零,它会打印两行输出。但是,如果 urls.count 为零,那么我只会得到一个打印语句,指出“urls.count ---> 0”

handleGetAllPhotoURLs ---> urls.count ---> 0//这一行总是被打印

handleGetAllPhotoURLs ---> urls.count ---> 21//只有当urls参数不为空时才会打印这一行

func handleGetAllPhotoURLs(pin: Pin, urls: [URL], error: Error?){
    print("handleGetAllPhotoURLs ---> urls.count  ---> \(urls.count)")

    let backgroundContext: NSManagedObjectContext! = dataController.backGroundContext
    if let error = error {
        print("func mapView(_ mapView: MKMapView, didSelect... \n\(error)")
        return
    }

    let pinId = pin.objectID
    backgroundContext.perform {
        let backgroundPin = backgroundContext.object(with: pinId) as! Pin
        backgroundPin.urlCount = Int32(urls.count)
        try? backgroundContext.save()
    }

    for (index, currentURL) in urls.enumerated() {
        URLSession.shared.dataTask(with: currentURL, completionHandler: { (imageData, response, error) in
            guard let imageData = imageData else {return}
            connectPhotoAndPin(dataController: self.dataController, currentPin:  pin , data: imageData, urlString: currentURL.absoluteString, index: index)
        }).resume()
    }
}

此外,我有一个 UILabel,它只在 urls.count 为零时显示自己,而我只想在 urls 为空时显示它。

现在,如果 urls 不为空,应用程序会非常快速地闪烁空消息 UILabel。这对我来说很有意义,因为 print 语句显示 urls 数组暂时为空。

当 urls.count 不为零时,我是否有办法确定避免向用户闪烁空消息 UILabel?

编辑:根据要求添加了下面的代码。调用下面的函数以在完成处理程序中获取 [URL]。然后完成处理程序被送入: func handleGetAllPhotoURLs(pin: Pin, urls: [URL], error: 错误?)

class func getAllPhotoURLs(currentPin: Pin, fetchCount count: Int, completion: @escaping (Pin, [URL], Error?)->Void)-> URLSessionTask?{
    let latitude = currentPin.latitude
    let longitude = currentPin.longitude
    let pageNumber = currentPin.pageNumber


    let url = Endpoints.photosSearch(latitude, longitude, count, pageNumber).url

    var array_photo_URLs = [URL]()
    var array_photoID_secret = [[String: String]]()
    var array_URLString = [String]()
    var array_URLString2 = [String]()
    var count = 0

    let task = URLSession.shared.dataTask(with: url) { data, response, error in
        guard let dataObject = data, error == nil else {
            DispatchQueue.main.async {
                completion(currentPin, [], error)
            }
            return
        }

        do {
            let temp = try JSONDecoder().decode(PhotosSearch.self, from: dataObject)
            temp.photos.photo.forEach{
                let tempDict = [$0.id : $0.secret]
                array_photoID_secret.append(tempDict)

                let photoURL = FlickrClient.Endpoints.getOnePicture($0.id, $0.secret)
                let photoURLString = photoURL.toString
                array_URLString.append(photoURLString)

                getPhotoURL(photoID: $0.id, secret: $0.secret, completion: { (urlString, error) in
                    guard let urlString = urlString else {return}
                    array_URLString2.append(urlString)
                    array_photo_URLs.append(URL(string: urlString)!)
                    count = count + 1
                    if count == temp.photos.photo.count {
                        completion(currentPin, array_photo_URLs, nil)
                    }
                })
            }
            completion(currentPin, [], nil)
            return
        } catch let conversionErr {
            DispatchQueue.main.async {
                completion(currentPin, [], conversionErr)
            }
            return
        }
    }
    task.resume()
    return task
}

最佳答案

do block 中,您调用了两次 completion。请看更正,

do {
    let temp = try JSONDecoder().decode(PhotosSearch.self, from: dataObject)
    if temp.photos.photo.isEmpty == false {
       temp.photos.photo.forEach{
        let tempDict = [$0.id : $0.secret]
        array_photoID_secret.append(tempDict)

        let photoURL = FlickrClient.Endpoints.getOnePicture($0.id, $0.secret)
        let photoURLString = photoURL.toString
        array_URLString.append(photoURLString)

        getPhotoURL(photoID: $0.id, secret: $0.secret, completion: { (urlString, error) in
            guard let urlString = urlString else {return}
            array_URLString2.append(urlString)
            array_photo_URLs.append(URL(string: urlString)!)
            count = count + 1
            if count == temp.photos.photo.count {
                completion(currentPin, array_photo_URLs, nil)
            }
        })
      }
    } else {
        completion(currentPin, [], nil)
    }
    return
}

关于swift - 如果执行嵌套异步调用,函数运行两次,否则运行一次。需要帮助预先确定何时会发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55625101/

有关swift - 如果执行嵌套异步调用,函数运行两次,否则运行一次。需要帮助预先确定何时会发生的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  3. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  4. ruby - 如何每月在 Heroku 运行一次 Scheduler 插件? - 2

    在选择我想要运行操作的频率时,唯一的选项是“每天”、“每小时”和“每10分钟”。谢谢!我想为我的Rails3.1应用程序运行调度程序。 最佳答案 这不是一个优雅的解决方案,但您可以安排它每天运行,并在实际开始工作之前检查日期是否为当月的第一天。 关于ruby-如何每月在Heroku运行一次Scheduler插件?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/8692687/

  5. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  6. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  7. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  8. ruby - rspec 需要 .rspec 文件中的 spec_helper - 2

    我注意到像bundler这样的项目在每个specfile中执行requirespec_helper我还注意到rspec使用选项--require,它允许您在引导rspec时要求一个文件。您还可以将其添加到.rspec文件中,因此只要您运行不带参数的rspec就会添加它。使用上述方法有什么缺点可以解释为什么像bundler这样的项目选择在每个规范文件中都需要spec_helper吗? 最佳答案 我不在Bundler上工作,所以我不能直接谈论他们的做法。并非所有项目都checkin.rspec文件。原因是这个文件,通常按照当前的惯例,只

  9. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  10. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

随机推荐