CURL到Swift中的URLRequest。 (MUX LIVE STREAMING API)

问题描述 投票:1回答:2

[您好,我试图在我的Swift应用程序中使用发布请求创建带有mux api的实时流。

这是cURL的外观。 MUX令牌ID和秘密ID在我的应用中快速定义:

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}

这是我的快速代码:

 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中定义。如果有人可以帮助我。谢谢

json swift curl http-live-streaming nsurlrequest
2个回答
1
投票

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

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()
}

0
投票

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

Authorization: Basic <some base64 string>

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

示例:

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

request.setValue("Basic \(encodedAuthString)", forHTTPHeaderField: "Authorization")
© www.soinside.com 2019 - 2024. All rights reserved.