首页 > 解决方案 > 尝试运行任务时,发送图像,收到错误代码 = 13“查询已取消”

问题描述

我目前正在使用 iOS 应用程序的图像选择器从相机角色中获取图片,然后尝试将其发送到 Web 服务器上的 PHP 脚本以将图像保存在另一端。

但是,当代码task.resume()行运行时,会引发此错误:

[发现] 发现扩展时遇到的错误:Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}

发生这种情况后,图像也不会保存在目的地。

didFinishPickingMediaWithInfo我已经阅读了有关此错误的其他几篇文章,并尝试将@objc.

我在 plist 中分配了隐私 - 照片库使用说明。我还允许任意负载。

通过这一切,错误仍然存​​在,所以如果有人能发现我的代码有任何问题,那将有很大帮助。我还将添加 PHP 脚本,以便您可以查看数据发送到的位置,谢谢。

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDataDelegate {

    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var uploadButton: UIButton!
    @IBOutlet weak var progressView: UIProgressView!
    @IBOutlet weak var progressLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        checkPermission()
    }

    func checkPermission() {
        let photoAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
        switch photoAuthorizationStatus {
        case .authorized:
            print("Access is granted by user")
        case .notDetermined:
            PHPhotoLibrary.requestAuthorization({
                (newStatus) in
                print("status is \(newStatus)")
                if newStatus ==  PHAuthorizationStatus.authorized {
                    /* do stuff here */
                    print("success")
                }
            })
            print("It is not determined until now")
        case .restricted:
            // same same
            print("User do not have access to photo album.")
        case .denied:
            // same same
            print("User has denied the permission.")
        }
    }

    @IBAction func uploadTapped(_ sender: UIButton) {
        let pickerController = UIImagePickerController()
        pickerController.delegate = self
        pickerController.sourceType = UIImagePickerController.SourceType.photoLibrary

        self.present(pickerController, animated: true, completion: nil)
    }

    @objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        imageView.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage

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

        uploadImage()
    }

    func uploadImage() {
        let imageData = imageView.image!.jpegData(compressionQuality: 1)

        if imageData == nil {
            return
        }

        self.uploadButton.isEnabled = false

        let uploadScriptURL = NSURL(string: "I've removed the URL for this question, but a valid URL to the PHP goes here")
        var request = URLRequest(url: uploadScriptURL! as URL)
        request.httpMethod = "POST"
        request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")

        let configuration = URLSessionConfiguration.default
        let session = URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)

        let task = session.uploadTask(with: request, from: imageData!)
        print(imageData!)
        task.resume()
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        let alert = UIAlertController(title: "Alert", message: error?.localizedDescription, preferredStyle: .alert)
        self.present(alert, animated: true, completion: nil)
        self.uploadButton.isEnabled = true
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
        let uploadProgress:Float = Float(totalBytesSent) / Float(totalBytesExpectedToSend)
        progressView.progress = uploadProgress
        let progressPercent = Int(uploadProgress * 100)
        progressLabel.text = "\(progressPercent)%"
    }

    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
        self.uploadButton.isEnabled = true
    }
}

PHP 脚本:

<?php
    $target_dir = "uploads";
    if(!file_exists($target_dir))
    {
        mkdir($target_dir, 0777, true);
    }
    $target_dir = $target_dir . "/" . basename($_FILES["file"]["name"]);
    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir)) {
        echo json_encode([
            "Message" => "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.",
            "Status" => "OK"
        ]);
    } else {
        echo json_encode([
            "Message" => "Sorry, there was an error uploading your file.",
            "Status" => "Error"
        ]);
    }

标签: phpiosswiftuiimagepickercontrollernsurlsessionuploadtask

解决方案


所以事实证明我的问题不是由这个错误引起的,而且似乎该错误实际上对代码没有任何影响 - 似乎可以忽略它。

就我而言,由于我的疏忽,代码无法正常工作。我试图发送的图像是 2.2MB,我没有意识到它返回了一个 HTML 错误代码 413,因为我正在测试的服务器上的上限是 2MB。

如果您遇到此类任务失败的问题,请确保在 urlSessionresponse的函数中打印出来。didReceive response这样您就可以检查返回的任何 HTML 错误。


推荐阅读