文件上传进度的 Notification-Observer 模式仅在文件较大时有效 - swift?

Notification-Observer pattern for file upload progress works only when the file is large - swift?

我有一个将图像上传到远程服务器的单一视图应用程序。当用户提交上传时,我使用第二个视图控制器显示为自定义弹出窗口并显示文件上传进度。上传完成后,自定义弹出窗口展开到第一个 viewController。我正在使用 notification-obersever 模式在两个 viewController 之间进行通信。

我的问题如下:当我上传大文件时,可以看到上传进度条,上传完成后自定义弹出窗口展开。当我上传一个小文件时,上传时间非常快,即使文件上传成功,也没有观察到上传进度,自定义弹出窗口也没有展开(见下面的代码)。

我不确定我是否正确设置了通知观察者模式?

第一个 VIEWCONTROLLER:

Alamofire.upload(
        multipartFormData: { multipartFormData in
            for(key, value) in sendParamters{
                multipartFormData.append((value.data(using: .utf8)!), withName: key)
            }

            for fileURL in arrayURLToUpload{
                print("fileURL: \(fileURL)")
                multipartFormData.append(fileURL, withName: "file[]")
            }
        },
            to: UPLOAD_URL,
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):

                    /**TRACK PROGRESS OF UPLOAD**/
                    upload.uploadProgress { progress in
                        print("ECNTERFILENAME: \(progress.fractionCompleted)")

                        let progress = progress.fractionCompleted

                        // NOTIFICATION - UPLOAD PROGRESS
                        NotificationCenter.default.post(name: notifcationName, object: nil, userInfo: ["progress": progress])
                    }
                    /***/


                    // 'responseJSON' FIRES WHEN UPLOAD IS COMPLETE
                    // IT ALSO TO FIRES WHEN THE IS INTERNET CONNECTIVITY ISSUES
                    upload.responseJSON { response in


                        // NOTIFICATION UPLOAD COMPLETE
                        NotificationCenter.default.post(name: uploadFinishName, object: nil, userInfo: ["response": response])
                    }


                case .failure(let encodingError):
                    print("UPLOAD ERROR")
                    print(encodingError)
                }
        }
    )

第二个VIEWCONTROLLER:

override func viewDidLoad() {
    super.viewDidLoad()

    self.createUploadObserver()
    self.createUploadFinishObserver()

    if txtLabelOutlet == nil{ // WHEN IMAGE('tickok') HAS REPLACED 'txtLabelOutlet'
        reformTxtLabel()
    }


    self.infoLabelOutlet.textColor = UIColor.black // CAN BE RED WHEN NETWORK CONNECTION IS LOST
    self.progressOutlet.progress = 0   
}



func createUploadObserver(){
    print("createUploadObserver ..")
    NotificationCenter.default.addObserver(forName: notifcationName, object: nil, queue: OperationQueue.main) { (notification) in

        guard
            var arrayN = notification.userInfo as? [String:Double],
            let num = arrayN["progress"] else{
                print("no valid data")
                return
        }
        // UPDATE PROGRESS BAR
        let progress = Float.init(num)
        self.progressOutlet.progress = progress

        // UPDATE LABEL
        let percent = Int(progress*100)
        print("percent: \(percent)")


        if let progressOut = self.txtLabelOutlet{
            print("OUTLET EXISTS!")
            progressOut.text = "\(percent)%"
        }else{
            print("OUTLET DOES NOT EXIST")
        }
    }
}




func createUploadFinishObserver(){
    print("createUploadFinishObserver ..")

    NotificationCenter.default.addObserver(forName: uploadFinishName, object: nil, queue: OperationQueue.main) { (notification) in

        print("notification.userInfo: \(notification.userInfo)")

        guard let response = notification.userInfo as? [String: DataResponse<Any>] else{
            print("Error completion response")
            return
        }

        guard
            let respObj = response["response"] as? DataResponse<Any>,
            let result = respObj.result as? Result<Any> else{return}


        if let value  = result.value{
            print("value: \(value)")
        }

        if result.description == "SUCCESS"{
            // UPLOAD COMPLETE
            // SHOW VIDEO CAPTURE
            print("upload success")


            if let progressOut = self.txtLabelOutlet{
                print("OUTLET EXISTS - REMOVE FROM SUPERVIEW")
                progressOut.removeFromSuperview()
            }else{
                print("OUTLET DOES NOT EXIST to remove from superview")
            }

            // ADD GREEN TICK IMAGE TO SHOW UPLOAD SUCCESS PROGRAMTICALLY
            let image = UIImage.init(named: "tickok")
            self.showCompleteTickImage(image: image!, completion: {

                // DELAY EXECUTION OF DIMISS POPUP BY 2 SECONDS
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    print("DISMISS PROGRESS POPUP")
                    // DISMISS POUP AND SHOW IMAGE CAPTURE AGAIN
                    self.performSegue(withIdentifier: "inwindme2", sender: self)

                }
            })


        }else{
            // HANDLE UPLOAD FAIL
            print("upload fail")
            self.infoLabelOutlet.text = "Network Connection Lost"
            self.infoLabelOutlet.textColor = UIColor.red
        }
    }
}

可以交换

self.createUploadFinishObserver()
self.createUploadObserver()

因为上传小文件时的popupVC好像还没有注册,所以完成post发生在观察之前,也可以在当前完成时开始上传弹出窗口,

self.present(popup,animated:true) {
  // start upload
}

如果继续

self.performSegue(///// 
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  // start upload 
}

要工作的通知中心,您的应用程序逻辑必须 100% 确定 post 在观察

之后发生