- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试将个人资料图片上传到服务器。但是我在执行 JSON 序列化
时出错。
日志中的错误信息是:
[Generic] Creating an image format with an unknown type is an error,
无法读取数据,因为它的格式不正确
从照片库中选择一张图片后,图片出现在用户界面中,但是图片没有成功上传到服务器,所以这可能就是我在进行 JSON 序列化时出错的原因。但我不知道为什么说格式不正确,因为我尝试上传 jpeg 格式的图像。
这是简化的代码。什么地方出了错? :(
import UIKit
class HomepageVC: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBAction func editProfilePictureButtonDidPressed(_ sender: Any) {
// users choose photo from library or camera
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
imagePickerController.allowsEditing = true
let actionSheet = UIAlertController(title: "Photo Source", message: "please choose your source", preferredStyle: .actionSheet)
// action camera
let actionCamera = UIAlertAction(title: "Camera", style: .default) { (action) in
if UIImagePickerController.isSourceTypeAvailable(.camera) {
imagePickerController.sourceType = .camera
self.present(imagePickerController, animated: true, completion: nil)
} else {
self.showAlert(alertTitle: "Opppss", alertMessage: "camera can't be used / not available", actionTitle: "OK")
print("camera can't be used / not available")
}
}
// action photo library
let actionPhotoLibrary = UIAlertAction(title: "Photo Library", style: .default) { (action) in
imagePickerController.sourceType = .photoLibrary
self.present(imagePickerController, animated: true, completion: nil)
}
//action cancel
let actionCancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
actionSheet.addAction(actionCamera)
actionSheet.addAction(actionPhotoLibrary)
actionSheet.addAction(actionCancel)
self.present(actionSheet, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
avatarImage.image = image
picker.dismiss(animated: true, completion: nil)
// call func of uploading file to PHP server
uploadAvatar()
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
// custom HTTP request body to upload image file
func createBodyWithParams(_ parameters: [String: String]?, filePathKey: String?, imageDataKey: Data, boundary: String) -> Data {
var body = Data();
if parameters != nil {
for (key, value) in parameters! {
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}
// kita set agar image yang di upload kemudian berformat .jpg
let filename = "avatar.jpg"
let mimetype = "image/jpg"
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimetype)\r\n\r\n")
body.append(imageDataKey)
body.appendString("\r\n")
body.appendString("--\(boundary)--\r\n")
return body as Data
}
// uploading image to server
func uploadAvatar() {
// get ID from Default variable
let id = userInfo!["id"] as! String
let url = URL(string: "http://localhost/Twitter/uploadAvatar.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let param = ["id" : id]
let boundary = "Boundary-\(UUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let imageData = UIImageJPEGRepresentation(avatarImage.image!, 0.5)
// if not compressed, return ... do not continue to code
if imageData == nil {
return
}
// constructing http body
request.httpBody = createBodyWithParams(param, filePathKey: "file", imageDataKey: imageData!, boundary: boundary)
// launc session
URLSession.shared.dataTask(with: request) { data, response, error in
DispatchQueue.main.async(execute: {
if error == nil {
// if error is nil, then show message from server
do {
// json containes $returnArray from php
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
// declare new parseJSON to store json
guard let parsedJSON = json else {
print("Error while parsing")
return
}
// get id from $returnArray["id"] in PHP - parseJSON["id"]
let id = parsedJSON["id"]
// successfully uploaded
if id != nil {
// save user information from Server
UserDefaults.standard.set(parsedJSON, forKey: "parsedJSON")
// if no ID from server then show the message from server
} else {
// get main queue to communicate back to user
DispatchQueue.main.async(execute: {
let message = parsedJSON["message"] as! String
self.showAlert(alertTitle: "opppps", alertMessage: message, actionTitle: "OK")
})
}
// error doing JSON serialization
} catch {
// get main queue to communicate back to user
DispatchQueue.main.async(execute: {
let message = error.localizedDescription
self.showAlert(alertTitle: "Sorry", alertMessage: message, actionTitle: "OK")
})
}
// error ketika koneksi ke server
} else {
// get main queue to communicate back to user
DispatchQueue.main.async(execute: {
let message = error!.localizedDescription
self.showAlert(alertTitle: "oppps", alertMessage: message, actionTitle: "OK")
})
}
})
}.resume()
}
}
// extend data
extension Data {
mutating func appendString(_ string : String) {
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
append(data!)
}
}
最佳答案
您的服务器数据正在打印以获取更多详细信息。例如服务器错误或任何其他详细信息。
URLSession.shared.dataTask(with: request) { data, response, error in
DispatchQueue.main.async(execute: {
// server data is convert in to string and print it
let strData = String.init(data: data!, encoding: String.Encoding.utf8)
print(strData )
})
}
服务器返回的响应不是JSON格式。您可以先使用该工具测试请求。
打印出来的错误码不是HTTP错误码,因为解析JSON失败
关于ios - 进行 JSON 序列化时出错,数据格式不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47863532/
我处理来自 AVFrame.data 的原始数据。此帧的像素格式为 AV_PIX_FMT_YUV420P。我想了解此数据位于哪个值范围内。 似乎 UV(在 YUV 方案中)必须在 [-128, 128
关闭。这个问题需要更多focused .它目前不接受答案。 想改善这个问题吗?更新问题,使其仅关注一个问题 editing this post . 去年关闭。 Improve this questio
Google Web Toolkits (GWT) RPC 调用的数据格式如何以及 IsSerializable 对象如何传输。我知道 Java Serializable 传输某种二进制格式,但是 G
我打算建立一个简单的音频接口(interface)。为此,我只想知道 ASIO 驱动程序通常以哪种格式将数据传递给程序?我无法从规范中找出这一点,也无法在其他地方找到它。我不想编写自己的驱动程序,我只
我正在编写一个平滑流客户端应用程序。在服务器端(带有Media Services扩展的IIS 7)上,我有一堆ISMV和ISMA文件,这些文件是使用Expression Encoder pro 4预先
我使用 JSON.stringify 和 JQuery.ajax() 将以下 JSON 对象从 .jsp 页面传递到 java servlet: {"bin":[{"binId":"0","binDe
我有一些来自 VLM telnet 服务的数据: show media : ( 1 broadcast - 0 vod ) cam1 type : br
我们正在导出公钥和私钥。私钥将由用 Magic 编写的非 .net 软件使用。开发人员对导出 key 的格式有疑问。是否有白皮书或其他资源来解释导出数据的格式? 最佳答案 关于导出的 blob 类型的
如何在 Altair 中创建多线图? 特别是,我有一个 pandas 数据框,如下所示: Commit Author Date Week Adds
我的数据格式类似于此示例中使用的 flare.json: 我只是想知道 d3 可缩放图表使用什么函数 来获取这种格式的数据 在 flare.json 中是这样的 { name: "stuff",
我正在尝试创建一些 JSON 用于使用 Highcharts 显示图表 http://www.highcharts.com/ 我复制了他们的一个例子: http://www.highcharts.co
我被要求编写一个读取 BSDF data format defined by Zemax 的函数此类文件的示例可在以下页面找到:BSDF file example 如果可能的话,我想只使用标准的 if
我为 CoreML 将 UIImage 转换为 CVPixelBuffer,但我想更改 RGB 像素,如 R/1.5、G/2、B/2.5。 我可以使用assumingMemoryBound(to :
我正在开发一个项目,我想展示网站中的各种文件如何相互交互。我认为使用 D3 这将是一个相当简单的任务,但现在我想知道我的 json 数据是如何排列的。这是我的数据示例: { "pages" : [{
我正在使用 Apache POI 构建一些 Excel 文件,我想确保某些单元格的类型为“Number”。 我尝试了以下方法: style.setDataFormat(HSSFDataForm
我有一些具有小数属性的实体。这些实体的属性显示在我整个 UI 的多个位置。 目前我发现自己在做: litWeight.Text = person.Weight.ToString("0.00"); 无处
首先介绍三个注解: @JsonAutoDetect (method/field):作用于方法或字段,用来表明,当生成json的时候忽略有该annotation的方法或字段 @JsonIgnore 过滤
我是 Azure 的新手,一直在使用 Azure Monitor 和 AZ Sentinel 进行日志记录和分析部分。我的审核日志从 AZ VM 中托管的第三方供应商安全设备流向 Syslog VM。
我有一些代码,例如: CellStyle cs2 = wb.createCellStyle(); CellStyle cs4 = wb.createCellStyle(); cs4.setDataFo
我正在尝试提取 YourKit 的“线程” View 中显示的数据(关于线程状态;主要是当每个线程“等待”或“可运行”时)。我已使用命令行导出实用程序为其支持的所有 View 生成所有格式。 导出目录
我是一名优秀的程序员,十分优秀!