Swift 中的 URLRequest 的 CURL。 (MUX 直播 API)

CURL to URLRequest in Swift. (MUX LIVE STREAMING API)

您好,我正在尝试在我的 swift 应用程序中通过 post 请求使用 mux api 创建实时流。

这就是 cURL 的样子。 MUX TOKEN ID 和 SECRET ID 在我的应用程序中定义 swift:

curl https://api.mux.com/video/v1/live-streams \
-H "Content-Type: application/json" \
-X POST \
-d '{ "playback_policy": "public", "new_asset_settings": { "playback_policy": "public" } }' \
-u ${MUX_TOKEN_ID}:${MUX_TOKEN_SECRET}

这是我在 swift 中的代码:

 func getStreamKeys() {


    let url = URL(string: "https://api.mux.com/video/v1/live-streams")!
    var request = URLRequest(url: url)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"
    let parameters: [String: Any] = [
        "playback_policy": "public",
        "new_asset_settings": ["playback_policy": "public"]
    ]
    request.httpBody = parameters.percentEncoded()

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data,
            let response = response as? HTTPURLResponse,
            error == nil else {                                              // check for fundamental networking error
            print("error", error ?? "Unknown error")
            return
        }

        guard (200 ... 299) ~= response.statusCode else {                    // check for http errors
            print("statusCode should be 2xx, but is \(response.statusCode)")
            print("response = \(response)")
            return
        }

        let responseString = String(data: data, encoding: .utf8)
        print("responseString = \(responseString)")
    }

    task.resume()


}

这是我得到的回复:

response = <NSHTTPURLResponse: 0x281c928e0> { URL: https://api.mux.com/video/v1/live-streams } { Status Code: 401, Headers {
"Cache-Control" =     (
    "max-age=0, private, must-revalidate"
);
"Content-Length" =     (
    69
);
"Content-Type" =     (
    "application/json; charset=utf-8"
);
Date =     (
    "Tue, 03 Mar 2020 22:34:45 GMT"
);
Server =     (
    "Mux API Server v1.89.12"
);
"x-request-id" =     (
    "FfjsHsz4jsEe_3oAcmYi"
);
} }

响应应该是这样的:

{
"data": {
"id": "QrikEQpEXp3RvklQSHyHSYOakQkXlRId",
"stream_key": "super-secret-stream-key",
"status": "idle",
"playback_ids": [
  {
    "policy": "public",
    "id": "OJxPwQuByldIr02VfoXDdX6Ynl01MTgC8w02"
  }
],
  "created_at": "1527110899"
}
}

我还需要传递 -u ${MUX_TOKEN_ID}:${MUX_TOKEN_SECRET} id 和 secret 是常量,应该定义在getStreamKeys。如果有人可以帮助我。谢谢

因此 curl 上的 -u 标志将值编码为 base64 并将其作为 header

传递

Authorization: Basic <some base64 string>

因此在 Swift 中,您必须对 ${MUX_TOKEN_ID}:${MUX_TOKEN_SECRET} 的值进行编码,然后将其传递到 header 字典中。

示例:

let authString = "\(MUX_TOKEN_ID):\(MUX_TOKEN_SECRET)"
let encodedAuthString = Data(authString).base64EncodedString()

request.setValue("Basic \(encodedAuthString)", forHTTPHeaderField: "Authorization")

您需要将身份验证添加到 api 调用,如下所述。 我还用 JSONSerialization 替换了你的 percentEncoded(),因为我不知道你那里有什么。

let MUX_TOKEN_ID: String = ""
let MUX_TOKEN_SECRET: String = ""

func getStreamKeys() {
    let url = URL(string: "https://api.mux.com/video/v1/live-streams")!
    var request = URLRequest(url: url)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

    let auth = "\(MUX_TOKEN_ID):\(MUX_TOKEN_SECRET)" // create string
    let base64Auth = Data(auth.utf8).base64EncodedString() // base64encode the string
    request.setValue("Basic \(base64Auth)", forHTTPHeaderField: "Authorization") // add auth to headers

    request.httpMethod = "POST"
    let parameters: [String: Any] = [
        "playback_policy": "public",
        "new_asset_settings": ["playback_policy": "public"]
    ]
    do {
        let jsonData = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
        request.httpBody = jsonData
        print(jsonData)
    } catch let e {
        print(e)
    }

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data,
            let response = response as? HTTPURLResponse,
            error == nil else {                                              // check for fundamental networking error
            print("error", error ?? "Unknown error")
            return
        }
        print(response)
        guard (200 ... 299) ~= response.statusCode else {                    // check for http errors
            print("statusCode should be 2xx, but is \(response.statusCode)")
            print("response = \(response)")
            return
        }

        let responseString = String(data: data, encoding: .utf8)
    }
    task.resume()
}