Swift: problem with Mandrill POST

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?

+4
source share
2 answers

Finally!!! thought to myself.

let to = ["email" : "kashif.izhar@gmail.com"]

it should be

let to = [["email" : "kashif.izhar@gmail.com"]]

Hope this helps someone

+1
source

I don’t know the framework (or even the programming language) you are using, but the answer seems very clear.

Here's the thing:

let to = ["email": " xyz@gmail.com "]

, ( ). , :

let to = [ "xyz@gmail.com" ]

Edit

, :

"to": [             {                  "email": "recipient.email@example.com",                  "name": " ",                  "type": "to"             }         ]

: .. "" .

+1

Source: https://habr.com/ru/post/1589081/


All Articles