gpt4 book ai didi

python - 线程 1 :EXC_BAD_INSTRACTION

转载 作者:可可西里 更新时间:2023-11-01 00:57:05 25 4
gpt4 key购买 nike

我收到错误 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 服务器,即使发生所有意外错误也可以。(顺便说一下,当我没有选择任何图像时,我想显示类似“错误”的警报)

最佳答案

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

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

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

关于python - 线程 1 :EXC_BAD_INSTRACTION,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44559869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com