在Swift 2.2中将带有图片的JSON发布到外部服务器,可以按照以下步骤进行操作:
NSDictionary
或者NSMutableDictionary
来创建一个字典对象,并添加键值对。let json: NSMutableDictionary = NSMutableDictionary()
json.setValue("John Doe", forKey: "name")
json.setValue(25, forKey: "age")
// 添加图片数据
let image = UIImage(named: "image.jpg")
let imageData = UIImageJPEGRepresentation(image!, 1.0)
json.setValue(imageData?.base64EncodedStringWithOptions(.Encoding64CharacterLineLength), forKey: "image")
let jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted)
let url = NSURL(string: "http://example.com/upload")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPBody = jsonData
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
if let error = error {
print("Error: \(error)")
} else if let data = data {
// 处理响应数据
let responseJSON = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
print("Response: \(responseJSON)")
}
}
task.resume()
这样,你就可以将带有图片的JSON发布到外部服务器了。请注意,这只是一个基本的示例,实际情况中可能需要根据具体需求进行适当的修改。
领取专属 10元无门槛券
手把手带您无忧上云