【问题标题】:Print statement are not getting printed打印语句未打印
【发布时间】:2018-10-20 05:53:04
【问题描述】:

为什么在我下面的代码中,在 AlamofireImage 下载图像后 viewWillAppear 块中的打印语句会跳过 viewWillAppear 块中的其余代码...

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)


    Alamofire.request("https://example.com/four.png").responseImage { response in
        debugPrint(response)

        print(response.request as Any)
        print(response.response as Any)
        debugPrint(response.result)

        if let image = response.result.value {
            print("image downloaded: \(image)")

            self.imageServer.append(image)

            print("ImageServer append Successful")
            print("The new number of images = \(self.imageServer.count)")

        }
    }


///////////THESE STATEMENTS ARE BEING SKIPPED/////////////////
    print("The new number of images = \(imageServer.count)")
    print("Test")
    trackedImages = loadedImagesFromDirectoryContents(imageServer)
    configuration.trackingImages = trackedImages
    configuration.maximumNumberOfTrackedImages = 1
    sceneView.session.run(configuration)
}

【问题讨论】:

  • 啊!!太好了,我读了你的评论后才意识到。非常感谢,您能否提供一些提示,告诉我如何让它按我的意愿工作?

标签: swift xcode alamofire arkit alamofireimage


【解决方案1】:

您可以使用completionHandler 来解决这个问题。这将在function 完成后执行。

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    fetchImage {
        print("The new number of images = \(imageServer.count)")
        trackedImages = loadedImagesFromDirectoryContents(imageServer)
        configuration.trackingImages = trackedImages
        configuration.maximumNumberOfTrackedImages = 1
        sceneView.session.run(configuration)
    }

}

func fetchImage(completion: @escaping ()->()) {
    Alamofire.request("https://example.com/four.png").responseImage { response in
        debugPrint(response)

        print(response.request as Any)
        print(response.response as Any)
        debugPrint(response.result)

        if let image = response.result.value {
            print("image downloaded: \(image)")

            self.imageServer.append(image)

            print("ImageServer append Successful")
            print("The new number of images = \(self.imageServer.count)")

        }
        completion()
    }
}

【讨论】:

  • 为什么不把 notified 代码放入完成闭包中?DispatchGroup 不适合单个异步操作。
  • 我同意,用completionHandler 做一个函数会更好。我可以编辑我的答案以获得更好的解决方案
  • 嗨,Jacob,我还有一个问题。当我将 ARReferenceImage 方法与 inGroupNamed 一起使用时,arkit 效果很好,但是当我尝试使用 Alamofire 添加我下载的图片时,arkit 检测到它并播放视频,但我在屏幕上看不到视频。知道为什么会发生这种情况,如果您愿意,我也可以上传源代码。谢谢