iOS 11 URLSessionDataTask的进度变量未显示正确的进度

时间:2018-02-19 22:10:13

标签: ios ios11 nsurlsessiondatatask

我需要找出上传任务的进度。但我只能使用URLSession的dataTask方法(而不是uploadTask方法)来创建任务。我也不能使用委托初始化程序来创建会话。要查找我在URLSessionDataTask的进度变量上使用KVO的进度,如下面的代码所示。

但是我的KVO值仅从0.95开始(而不是从0开始)。感谢在这种情况下如何找到进展的任何帮助。

我正在使用this sample code,并根据我的需要进行了更改:

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDataDelegate  {
    private var progressKVOContext = 0

    @IBOutlet weak var myImageView: UIImageView!
    @IBOutlet weak var uploadButton: UIButton!
    @IBOutlet weak var imageUploadProgressView: UIProgressView!
    @IBOutlet weak var progressLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib. 
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func uploadButtonTapped(_ sender: AnyObject) {

        let myPickerController = UIImagePickerController()
        myPickerController.delegate = self;
        myPickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary

        self.present(myPickerController, animated: true, completion: nil)

    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [AnyHashable: Any])
    {
        myImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage

        myImageView.backgroundColor = UIColor.clear
        self.dismiss(animated: true, completion: nil)

        uploadImage()

    }

    func uploadImage()
    {
        let imageData = UIImageJPEGRepresentation(myImageView.image!, 1)

        if(imageData == nil )  { return }

        self.uploadButton.isEnabled = false


        let uploadScriptUrl = URL(string:"http://www.swiftdeveloperblog.com/http-post-example-script/")
        var request = URLRequest(url: uploadScriptUrl!)
        request.httpMethod = "POST"
        request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")

        let configuration = URLSessionConfiguration.default
        let session = URLSession(configuration: configuration)
        let task = session.dataTask(with: request) { (data, urlResp, error) in
            print("\(String(describing: data))")
        }
        if #available(iOS 11.0, *) {
            task.progress.addObserver(self, forKeyPath: #keyPath(Progress.fractionCompleted), options: [.new], context: &progressKVOContext)
            print("KVO set here")

        } else {
            // Fallback on earlier versions
        }

        task.resume()
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if context == &progressKVOContext && keyPath == #keyPath(Progress.fractionCompleted), let progress = object as? Progress {
            var progressFractionCompleted = (progress.totalUnitCount == -1) ? 1.0 : progress.fractionCompleted

            if progressFractionCompleted == 1 {
                print("progressFractionCompleted here = \(progressFractionCompleted)")

//                try? removeObserver(self, forKeyPath: #keyPath(Progress.fractionCompleted), context: &progressKVOContext)
            }

            if progressFractionCompleted > 1 {
                print("Inside greater \(progressFractionCompleted)")
                progressFractionCompleted = 1/progressFractionCompleted
            }
            print("progressFractionCompleted = \(progressFractionCompleted)")
        } else {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        }
    }
}

0 个答案:

没有答案