线程1:EXC_BAD_INSTRACTION

时间:2017-06-15 06:13:02

标签: python ios swift django

我收到错误Thread1:EXC_BAD_INSTRACTION。 我正在制作Swift应用程序,我想在我的应用程序中创建一个系统,将图像上传到我的Django服务器。当我没有选择任何图像并且我将“发送”按钮发送到服务器时,会发生此错误。 error 现在,PhotoController(它用于系统)是

import Foundation
import MobileCoreServices
import UIKit
class PhotoController:UIViewController,UINavigationControllerDelegate,UIImagePickerControllerDelegate{

    @IBOutlet weak var myActivityIndicator: UIActivityIndicatorView!
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var myImageView: UIImageView!
    private var imagePicker:UIImagePickerController!

    @IBAction func uploadButtonTapped(_ sender: Any) {
        myImageUploadRequest()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        label.adjustsFontSizeToFitWidth = true
        label.minimumScaleFactor = 0.5
        label.text = "Tap the PhotoSelect or Camera to upload a picture"
     }

    @IBAction func PhotoSelect(_ sender: Any) {
        let myPickerController = UIImagePickerController()
        myPickerController.delegate = self;
        myPickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary

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

    }

    @IBAction func Camera(_ sender: Any) {
        let sourceType:UIImagePickerControllerSourceType = UIImagePickerControllerSourceType.camera
        // カメラが利用可能かチェック
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){
            // インスタンスの作成
            let cameraPicker = UIImagePickerController()
            cameraPicker.sourceType = sourceType
            cameraPicker.delegate = self
            self.present(cameraPicker, animated: true, completion: nil)

        }
        else{
            label.text = "error"   
        }
    } 
    // 撮影が完了時した時に呼ばれる
    func imagePickerController(_ imagePicker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

        if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
            myImageView.contentMode = .scaleAspectFit
            myImageView.image = pickedImage

        }

        //閉じる処理
        imagePicker.dismiss(animated: true, completion: nil)
        label.text = "Tap the Send to save a picture"

    }

    // 撮影がキャンセルされた時に呼ばれる
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
        label.text = "Canceled"
    }

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

    func myImageUploadRequest()
    {

        let myUrl = NSURL(string: "http://localhost:8000/admin/accounts/post/");
        let request = NSMutableURLRequest(url:myUrl! as URL);
        request.httpMethod = "POST";
        //ユーザーごとに割り振りたい
        let param = [
            "firstName"  : "Sergey",
            "lastName"    : "Kargopolov",
            "userId"    : "9"
        ]

        let boundary = generateBoundaryString()

        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")


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

        if(imageData==nil)  { return; }

        request.httpBody = createBodyWithParameters(parameters: param, filePathKey: "file", imageDataKey: imageData! as NSData, boundary: boundary) as Data


        myActivityIndicator.startAnimating();

        let task = URLSession.shared.dataTask(with: request as URLRequest) {
            data, response, error in

            if error != nil {
                print("error=\(error)")
                return
            }

            // You can print out response object
            print("******* response = \(response)")

            // Print out reponse body
            let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
            print("****** response data = \(responseString!)")

            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary

                DispatchQueue.main.async {
                    self.myActivityIndicator.stopAnimating()
                    self.myImageView.image = nil;
                }

            }catch
            {
                print(error)
            }

        }

        task.resume()
    }
    func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
        let body = NSMutableData();

        if parameters != nil {
            for (key, value) in parameters! {
                body.appendString(string: "--\(boundary)\r\n")
                body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                body.appendString(string: "\(value)\r\n")
            }
        }

        let filename = "user-profile.jpg"
        let mimetype = "image/jpg"

        body.appendString(string: "--\(boundary)\r\n")
        body.appendString(string: "Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
        body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
        body.append(imageDataKey as Data)
        body.appendString(string: "\r\n")
        body.appendString(string: "--\(boundary)--\r\n")

        return body
    }

    func generateBoundaryString() -> String {
        return "Boundary-\(NSUUID().uuidString)"
    }

}
extension NSMutableData {

    func appendString(string: String) {
        let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
        append(data!)
    }
}

追溯是

fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb) 

我无法理解为什么会发生这种错误,因为我在本部分中为意外的事情编写了if语句

let task = URLSession.shared.dataTask(with: request as URLRequest) {
            data, response, error in

            if error != nil {
                print("error=\(error)")
                return
            }
            // You can print out response object
            print("******* response = \(response)")
            // Print out reponse body
            let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
            print("****** response data = \(responseString!)")
            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
                DispatchQueue.main.async {
                    self.myActivityIndicator.stopAnimating()
                    self.myImageView.image = nil;
                }

            }catch
            {
                print(error)
            }

        }

我该如何解决这个问题?我的目标是在我的应用程序中创建一个系统,将一个图像上传到我的Django服务器,即使发生了所有意外错误也没问题。(顺便说一下,当我没有选择任何图像时,我想显示警告,就像“错误”)

2 个答案:

答案 0 :(得分:2)

发生错误是因为myImageView为nil而你试图打开它。 你可以对myImageView.image进行零检查

if myImageView.image!= nil {
let imageData = UIImageJPEGRepresentation(myImageView.image!, 1)

        if(imageData==nil)  { return; }
}

答案 1 :(得分:1)

好的,所以你的应用程序在这里崩溃了:

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

这表明myImageView.image为零,这可能是由几件事引起的。

  1. myImageView实际上没有图片。
  2. myImageView @IBOutlet未按照上述评论中的建议正确连接
  3. 你有一张支票:

    if(imageData==nil)  { return; }
    

    但这只是一行,你可以看到:)

    你可以做的是对你的myImageView.image进行展开,只有当它出现时,你才会继续,否则你会从函数返回。

    看起来像这样:

    guard let myImage = myImageView.image else {
        return
    }
    

    现在您知道您的图片具有有效值并可以安全地继续。

    所以,你的整个函数看起来像这样:

    func myImageUploadRequest()
    {
        let myUrl = NSURL(string: "http://localhost:8000/admin/accounts/post/");
        let request = NSMutableURLRequest(url:myUrl! as URL);
        request.httpMethod = "POST";
        //ユーザーごとに割り振りたい
        let param = [
            "firstName"  : "Sergey",
            "lastName"    : "Kargopolov",
            "userId"    : "9"
        ]
    
        let boundary = generateBoundaryString()
    
        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
    
        guard let myImage = myImageView.image else {
            return
        }
    
        let imageData = UIImageJPEGRepresentation(myImage, 1)
    
        if(imageData==nil)  { return; }
    
        request.httpBody = createBodyWithParameters(parameters: param, filePathKey: "file", imageDataKey: imageData! as NSData, boundary: boundary) as Data
    
    
        myActivityIndicator.startAnimating();
    
        let task = URLSession.shared.dataTask(with: request as URLRequest) {
            data, response, error in
    
            if error != nil {
                print("error=\(error)")
                return
            }
    
            // You can print out response object
            print("******* response = \(response)")
    
            // Print out reponse body
            let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
            print("****** response data = \(responseString!)")
    
            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
    
                DispatchQueue.main.async {
                    self.myActivityIndicator.stopAnimating()
                    self.myImageView.image = nil;
                }
    
            }catch
            {
                print(error)
            }
    
        }
    
        task.resume()
    }
    

    希望对你有所帮助。