将用户添加到SWIFT 2

时间:2016-01-29 11:11:22

标签: swift mailchimp

我正在使用MailChimp进行电子邮件营销服务。现在我想将用户添加到我的订阅列表中,但它将无效的电子邮件视为JSON响应。我的代码如下。

      var url = "https://us4.api.mailchimp.com/2.0/lists/subscribe"

    let request = NSMutableURLRequest(URL: NSURL(string: url)!)

    let session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let params = ["apikey":"******************-us4", "id":"*******", "email":["email":email, "euid": "", "leid": ""], "merge_vars":["FNAME": name,"LNAME": ""], "double_optin": "false"]
    request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])


    let task = session.dataTaskWithRequest(request) { data, response, error in
        guard data != nil else {
            print("no data found: \(error)")
            return
        }



        do {
            if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {

                print("Success: \(String(json))")
    } catch let parseError {
            print(parseError)                                                          // Log the error thrown by `JSONObjectWithData`
            let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("Error could not parse JSON: '\(jsonStr)'")
        }
    }

    task.resume()

1 个答案:

答案 0 :(得分:1)

我尝试了相同但与我的mailchimp API完美配合。根据mailchimp官方文档(https://apidocs.mailchimp.com/api/2.0/lists/subscribe.php),您的json格式是正确的。所以请确保以下

1)确保您的API密钥正确无误。

2)确保您的列表ID正确无误。

3)重新检查您的网络防火墙

4)确保您的电子邮件不在当前列表中。