Reputation: 609
var urlString = ""
let url = NSURL(string: urlString)
let theRequest = NSMutableURLRequest(URL: url!)
theRequest.HTTPMethod = "POST"
let parameters = []
var err:NSError!
do{
theRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: [])
}
catch let error as NSError{
err = error
theRequest.HTTPBody = nil
}
theRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
theRequest.addValue("application/json", forHTTPHeaderField: "Accept")
Here I am using a 3rd party class library for a signature . How can I POST it to webservices in the form an image?
Upvotes: 0
Views: 3771
Reputation: 71854
Simple example for you:
//create session
var urlSession : NSURLSession!
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
urlSession = NSURLSession(configuration: configuration)
func updateUserDetails(image : UIImage? , dictUserDetails: [String: String?] ,completionClosure: (repos :NSDictionary) ->()) {
let request = NSMutableURLRequest(URL: NSURL(string:"Your URL" )!)
request.HTTPMethod = "POST"
let boundary = generateBoundaryString()
let token = getUserToken() as String
request.addValue("Token " + token, forHTTPHeaderField: "Authorization") // add token if you need
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
guard image != nil else {
request.HTTPBody = createBodyWithParameters(dictUserDetails, filePathKey: "profile_pic", imageDataKey: nil, boundary: boundary)
let postDataTask = self.urlSession.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if (error != nil) {
print(error!.localizedDescription)
}
if (data != nil) {
if let jsonResult: NSDictionary = (try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as? NSDictionary
{
completionClosure(repos: jsonResult)
}
else
{
completionClosure(repos: NSDictionary())
}
} else {
completionClosure(repos: NSDictionary())
}
})
postDataTask.resume()
return
}
let imageData = UIImageJPEGRepresentation(image!, 0.3)
request.HTTPBody = createBodyWithParameters(dictUserDetails, filePathKey: "profile_pic", imageDataKey: imageData, boundary: boundary)
let postDataTask = self.urlSession.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if (error != nil) {
print(error!.localizedDescription)
}
if (data != nil) {
if let jsonResult: NSDictionary = (try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as? NSDictionary
{
completionClosure(repos: jsonResult)
}
else
{
completionClosure(repos: NSDictionary())
}
} else {
completionClosure(repos: NSDictionary())
}
})
postDataTask.resume()
}
Helper Functions:
//Generate boundary
func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().UUIDString)"
}
//create body
func createBodyWithParameters(parameters: [String: String?]?, filePathKey: String?, imageDataKey: NSData?, boundary: String) -> NSData {
let body = NSMutableData()
if parameters != nil {
for (key, value) in parameters! {
if value != nil {
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value!)\r\n")
}
}
}
if imageDataKey != nil
{
let filename = "user-profile.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.appendData(imageDataKey!)
body.appendString("\r\n")
body.appendString("--\(boundary)--\r\n")
}
return body
}
Now you can use it this way:
updateUserDetails(yourImage, dictUserDetails: [
//parameters example
"date_of_birth": birthDate,
"first_name": firstName,
"last_name" : lastName,
"email" : email,
"phone_number" : phoneNumber,
"address" : address,
"martial_status" : userMaritialStatus
], completionClosure: { (repos) -> () in
print(repos)
})
Hope it will help.
Upvotes: 2
Reputation: 228
You did not say which third party library you are using, so you can use Alamofire
for it, using this code:
Alamofire.upload(
.POST,
"your_API_URL_here",
multipartFormData: { multipartFormData in
if let _ = image {
if let imageData = UIImageJPEGRepresentation(image!, 1.0) {
multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "file.jpeg", mimeType: "image/jpeg")
} else {
print(image)
}
}
}, encodingCompletion: {
encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
switch response.result {
case .Success:
print("Success")
case .Failure(let error):
print(error)
}
}
case .Failure(let encodingError):
print(encodingError)
}
}
)
}
} catch _ {
}
Upvotes: 1