Search code examples
jsonswiftcurlhttp-live-streamingnsurlrequest

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


Hello I am trying to create a live stream with mux api with a post request in my swift app.

This is what the cURL looks like. The MUX TOKEN ID & SECRET ID are defined in my app in 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}

This is my code in 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()


}

This is the response I get:

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"
);
} }

This is how the response should be:

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

I still need to pass -u ${MUX_TOKEN_ID}:${MUX_TOKEN_SECRET} the id and secret are constant and should be defined in the getStreamKeys. If someone can help me with it. Thanks


Solution

  • You'll need to add the auth to the api call as described below. I also replaced your percentEncoded() with JSONSerialization as I do not know what you have in there.

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