Image(or video) posting to server in Swift

ぃ、小莉子 提交于 2019-12-05 18:44:57

If you want to upload image in json body you need to encode it. Suppose you have a UIImage instance image

let data = UIImageJPEGRepresentation(image, 0.5)
let encodedImage = data.base64EncodedStringWithOptions(.allZeros)

Now it is encoded as base64 string. We can use it in json body.

let parameters = ["image": encodedImage, "otherParam": "otherValue"]

let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: "YOUR_URL")!)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"

var error: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: .allZeros, error: &error)

if let error = error {
    println("\(error.localizedDescription)")
}

let dataTask = session.dataTaskWithRequest(request) { data, response, error in
    // Handle response
}

dataTask.resume()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!