【问题标题】:Convert Parameters to Base64 Encoded String for API Call using Alamofire使用 Alamofire 将参数转换为 API 调用的 Base64 编码字符串
【发布时间】:2023-03-20 01:52:01
【问题描述】:

我正在尝试使用 Mixpanel 在我的 OS X 应用程序中跟踪事件。以下是他们的 API 文档:https://mixpanel.com/help/reference/http#tracking-via-http

我正在尝试发送带有事件名称和一堆属性的偶数。其中一个属性是文档中看到的令牌。看起来我需要将参数转换为字符串,然后对它们进行 base64 编码。最好的方法是什么?

我为此使用 Alamofire,参数是 Alamofire 参数。

这些是 Mixpanel 对 Base64 编码的要求

To Base64 encode data for the Mixpanel API, you should use the following characters:

ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
0123456789+/=

Mixpanel will only accept padded Base64 requests.

到目前为止,这是我的代码。我只是不知道如何对参数进行base64编码。

var headers: HTTPHeaders = [
    "content-type": "application/json"
]

var parameters:Parameters = [String : Any]()
parameters["event"] = "hello world"

var properties = [String:String]
props["token"] = "INSERT_TOKEN_HERE"
parameters["properties"] = properties

var url = "http://api.mixpanel.com/track/?data=\()" //after the data= is where the base64 encoded parameters are supposed to go

Alamofire.request(url, method: .post, parameters: nil , encoding: JSONEncoding.default, headers: headers)
    .responseJSON { (response) in
    switch response.result {
    case .success(let value):
        print ("return: \(value)")
    case .failure(let error):
        print ("error: \(error)")
    }
}

【问题讨论】:

  • 顺便说一句,MixPanel 有自己的 iOS SDK,似乎可以让您摆脱构建他们时髦请求的杂草。 mixpanel.com/help/reference/swift
  • 所以他们的 iOS SDK 的问题是它不支持 OS X 应用程序。我将 iOS SDK 用于 iOS 应用程序!

标签: swift macos alamofire swift4


【解决方案1】:

我们可以从他们的例子中转换data

http://api.mixpanel.com/track/?data=eyJldmVudCI6ICJnYW1lIiwgInByb3BlcnRpZXMiOiB7ImlwIjogIjEyMy4xMjMuMTIzLjEyMyIsICJkaXN0aW5jdF9pZCI6ICIxMzc5MyIsICJ0b2tlbiI6ICJlM2JiNDEwMDMzMGMzNTcyMjc0MGZiOGM2ZjVhYmRkYyIsICJ0aW1lIjogMTI0NTYxMzg4NSwgImFjdGlvbiI6ICJwbGF5In19

所以我们可以这样检查:

let data = Data(base64Encoded: "eyJldmVudCI6ICJnYW1lIiwgInByb3BlcnRpZXMiOiB7ImlwIjogIjEyMy4xMjMuMTIzLjEyMyIsICJkaXN0aW5jdF9pZCI6ICIxMzc5MyIsICJ0b2tlbiI6ICJlM2JiNDEwMDMzMGMzNTcyMjc0MGZiOGM2ZjVhYmRkYyIsICJ0aW1lIjogMTI0NTYxMzg4NSwgImFjdGlvbiI6ICJwbGF5In19")
let string = String(data: data!, encoding: .utf8)!
print(string)

这向我们展示了他们的 JSON 结构:

{
    "event": "game",
    "properties": {
        "ip": "123.123.123.123",
        "distinct_id": "13793",
        "token": "e3bb4100330c35722740fb8c6f5abddc",
        "time": 1245613885,
        "action": "play"
    }
}

这样我们就可以自己编写代码来构建类似的结构:

let dictionary: [String : Any] = [
    "event": "hello world",
    "properties": [
        "token": "INSERT_TOKEN_HERE"
    ]
]

let data = try! JSONSerialization.data(withJSONObject: dictionary)
let base64Representation = data.base64EncodedString()
let parameters = ["data": base64Representation]

let url = "http://api.mixpanel.com/track/"

Alamofire.request(url, method: .get, parameters: parameters, encoding: URLEncoding.default)
    .responseJSON { (response) in
        switch response.result {
        case .success(let value):
            print("return:", value)
        case .failure(let error):
            print("error:", error)
        }
}

注意,我将其设置为GET(因为看起来整个请求都在 URL 中),我使用了URLEncoding,因为 Alamofire 没有构建 JSON 主体。另外,我删除了 headers 的东西,因为你应该尽可能让 Alamofire 为你处理这些东西。

【讨论】:

  • 太棒了!这是我需要的两行 let data = try! JSONSerialization.data(withJSONObject: dictionary); let base64Representation = data.base64EncodedString() 也感谢所有其他注释。我做了这些改变。 URLEncoding 和 JSONEncoding 有什么区别?我还删除了参数字段,就像这样let url = "https://api.mixpanel.com/track/?data=\(base64Representation)" 可以吗?
  • URLEncoding 将请求编码为 URL,JSONEncoding 构建 JSON 请求并将其放入请求正文中。但是由于 MixPanel 的怪异 API,您必须自己进行 JSON 编码,然后 base64 将其编码为 URL。因此URLEncoding。在回答自己构建 URL 时,这有点脆弱,不推荐。我宁愿让 Alamofire 为你做这件事。如果 base64 编码的字符串中有一个 + 怎么办:这是许多 Web 服务上的一个特殊字符,不能在没有编码的情况下放入 URL(尽管 MixPanel 可能接受它)。这取决于你。
  • 完美。非常感谢!
猜你喜欢
  • 2019-02-16
  • 2018-08-05
  • 2014-04-08
  • 1970-01-01
  • 2019-08-16
  • 1970-01-01
  • 2012-11-12
  • 2018-04-14
  • 2010-10-26
相关资源
最近更新 更多