我有一张图片,我试图通过我的IOS应用程序发送到rails应用程序。
第1步:
这会抓取UIView中的图像
@IBOutlet var notifier: UILabel!
@IBOutlet var image: UIImage
@IBAction func Build(sender: AnyObject) {
let image_data = UIImagePNGRepresentation(image.image!)
self.service.createNewImage(notifier: notifier, image: image_data!)
}
第2步:
这是服务
func createNewImage(notifier: UILabel, image: NSData) {
let dataDictionary = ["image_data": image]
self.post("image/build", data: dataDictionary).responseJSON { (response) -> Void in
if(response.description[response.description.startIndex] as Character == "S") {
notifier.text = "This should be success"
} else {
notifier.text = "failure"
}
}
}
此代码目前导致错误:*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (NSConcreteMutableData)'
如何打包图像以通过API发送?
备注:
我认为这个问题特别来自这条线:
self.post("image/build", data: dataDictionary).responseJSON { (response) -> Void in
帖子定义为:
func post(path: String) -> Request {
return self.post(path, data: NSDictionary())
}
func post(path: String, data: NSDictionary) -> Request {
let url = self.url_from_path(path)
return self.client.request(.POST, url, parameters: data as? [String : AnyObject] , encoding: ParameterEncoding.JSON,
headers: self.getHeaders())
}
func patch(path: String, data: NSDictionary) -> Request {
let url = self.url_from_path(path)
return self.client.request(.PATCH, url, parameters: data as? [String : AnyObject] , encoding: ParameterEncoding.JSON,
headers: self.getHeaders())
}
答案 0 :(得分:0)
这有效:
let strBase64:String = image.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
let dataDictionary = ["image_data": strBase64]
您只需将无法放入JSON的NSData转换为可以放入JSON的base64字符串