I am trying to send an email through the Mandrill API. Below I found a quick code here for the HTTP POST JSON method:
func createRequest(myUrl : String, type : String, params : NSDictionary?, completion : (AnyObject?, NSError?)->Void ){
var url = NSURL(string: myUrl)
var request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 60.0)
if params != nil {
var data = NSJSONSerialization.dataWithJSONObject(params!, options: NSJSONWritingOptions.PrettyPrinted, error: nil)
request.setValue("\(data!.length)", forHTTPHeaderField: "Content-Length")
request.HTTPBody = data
}
request.setValue("application/json", forHTTPHeaderField:"Content-type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPMethod = type
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(),
completionHandler: {(response: NSURLResponse!, data: NSData!, error: NSError!) in
var returnedObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableLeaves, error: nil)
completion(returnedObject,error)
})
}
Now I set my url and parameters as follows:
let url = "https://mandrillapp.com/api/1.0/messages/send.json"
let to = ["email" : "xyz@gmail.com"]
let message = [
"from_email" : "noreply@abc.com",
"from_name" : "abc",
"subject" : "Message through abc",
"text" : "sample message",
"to" : to
]
let params = [
"key": "myKey",
"message" : message
]
Then I call this function as follows:
createRequest(url, type: "POST", params: params, completion: {(returnedObject : AnyObject?, error : NSError?)in
if (returnedObject != nil) {
println("data = \(returnedObject)")
}
})
But I get the error:
data = Optional({
code = "-2";
message = "Validation error: {\"message\":{\"to\":[\"Please enter an array\"]}}";
name = ValidationError;
status = error;
})
What am I doing wrong?