Home > Net >  Cannot get proper channel icon using YouTube API, the result is not .png .jpg extension
Cannot get proper channel icon using YouTube API, the result is not .png .jpg extension

Time:08-11

I'm trying to get channel's icons from YouTube API in my Swift test app, but I don't know how to properly display such images (they have no extensions to them), and how to convert them. My search in the internet gave no results.

Here you can check it out

https://developers.google.com/youtube/v3/docs/channels/list?apix_params={"part":["snippet,contentDetails,statistics"],"id":["UC_x5XG1OV2P6uZZ5FSM9Ttw"]}

The result YouTube api gives is not .png .jpg file, please check "thumbnails" "url" has no extension to it

{
  "kind": "youtube#channelListResponse",
  "etag": "1W0m-GU_K3MSAyhDuW1YSFiT7yA",
  "pageInfo": {
    "totalResults": 1,
    "resultsPerPage": 5
  },
  "items": [
    {
      "kind": "youtube#channel",
      "etag": "oT7_7pClsrMvTCMkyd7e5M1cfn0",
      "id": "UC_x5XG1OV2P6uZZ5FSM9Ttw",
      "snippet": {
        "title": "Google Developers",
        "description": "The Google Developers channel features talks from events, educational series, best practices, tips, and the latest updates across our products and platforms.\n\nSubscribe to Google Developers → https://goo.gle/developers\n",
        "customUrl": "googledevelopers",
        "publishedAt": "2007-08-23T00:34:43Z",
        "thumbnails": {
          "default": {
            "url": "https://yt3.ggpht.com/ytc/AMLnZu-oDvWEJ-WfN9bgxQB2YAlnjC2uqN_c7JQZvX9Ikfg=s88-c-k-c0x00ffffff-no-rj",
            "width": 88,
            "height": 88
          },
          "medium": {
            "url": "https://yt3.ggpht.com/ytc/AMLnZu-oDvWEJ-WfN9bgxQB2YAlnjC2uqN_c7JQZvX9Ikfg=s240-c-k-c0x00ffffff-no-rj",
            "width": 240,
            "height": 240
          },
          "high": {
            "url": "https://yt3.ggpht.com/ytc/AMLnZu-oDvWEJ-WfN9bgxQB2YAlnjC2uqN_c7JQZvX9Ikfg=s800-c-k-c0x00ffffff-no-rj",
            "width": 800,
            "height": 800
          }
        },
        "localized": {
          "title": "Google Developers",
          "description": "The Google Developers channel features talks from events, educational series, best practices, tips, and the latest updates across our products and platforms.\n\nSubscribe to Google Developers → https://goo.gle/developers\n"
        },
        "country": "US"
      },
      "contentDetails": {
        "relatedPlaylists": {
          "likes": "",
          "uploads": "UU_x5XG1OV2P6uZZ5FSM9Ttw"
        }
      },
      "statistics": {
        "viewCount": "207367157",
        "subscriberCount": "2250000",
        "hiddenSubscriberCount": false,
        "videoCount": "5599"
      }
    }
  ]
}

However Postman (https://www.postman.com/) is able to display image somehow. But if I copy and paste "image url"

https://yt3.ggpht.com/ytc/AMLnZu-oDvWEJ-WfN9bgxQB2YAlnjC2uqN_c7JQZvX9Ikfg=s800-c-k-c0x00ffffff-no-rj

into my browser, nothing happends -> page not loads, and the same happens in my swift app.

If anybody knows solution, your help is eally appreciated!


UPDATE to Ameermuhammed:

Adding logs. Something is wrong. I want to note that I'm not using Auth 2.0 with api, but requesting data only with dedicated API key YouTube provided me with. However this shouldn't be the case since Postman is still able to load image. For now I'm trying to figure it out

2022-08-11 15:56:04.084652 0300 YouTubeAPI[60421:2201169] Task .<3> finished with error [-1200] Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={NSErrorFailingURLStringKey=https://yt3.ggpht.com/_1Z4I2qpWaCN9g3BcDd3cVA9MDHOG43lE1YNWDNkKro49haGxkjwuFK-I8faWTKM6Jle9qb4ag=s240-c-k-c0x00ffffff-no-rj, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask .<3>, _NSURLErrorRelatedURLSessionTaskErrorKey=( "LocalDataTask .<3>" ), NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://yt3.ggpht.com/_1Z4I2qpWaCN9g3BcDd3cVA9MDHOG43lE1YNWDNkKro49haGxkjwuFK-I8faWTKM6Jle9qb4ag=s240-c-k-c0x00ffffff-no-rj, NSUnderlyingError=0x600003256100 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, _kCFNetworkCFStreamSSLErrorOriginalValue=-9816, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9816, _NSURLErrorNWPathKey=satisfied (Path is satisfied), interface: en0}}, _kCFStreamErrorCodeKey=-9816} 2022-08-11 15:56:04.127253 0300 YouTubeAPI[60421:2201170] [connection] nw_socket_handle_socket_event [C4.1:3] Socket SO_ERROR [54: Connection reset by peer] 2022-08-11 15:56:04.128643 0300 YouTubeAPI[60421:2201170] Connection 4: received failure notification 2022-08-11 15:56:04.128897 0300 YouTubeAPI[60421:2201172] [boringssl] boringssl_metrics_log_metric_block_invoke(153) Failed to log metrics 2022-08-11 15:56:04.129070 0300 YouTubeAPI[60421:2201170] Connection 4: received ECONNRESET with incomplete TLS handshake - generating errSSLClosedNoNotify 2022-08-11 15:56:04.129495 0300 YouTubeAPI[60421:2201170] Connection 4: failed to connect 3:-9816, reason -1 2022-08-11 15:56:04.129622 0300 YouTubeAPI[60421:2201170] Connection 4: encountered error(3:-9816) 2022-08-11 15:56:04.131593 0300 YouTubeAPI[60421:2201170] Task .<4> HTTP load failed, 0/0 bytes (error code: -1200 [3:-9816]) 2022-08-11 15:56:04.132103 0300 YouTubeAPI[60421:2201169] Task .<4> finished with error [-1200] Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={NSErrorFailingURLStringKey=https://yt3.ggpht.com/ytc/AMLnZu9uvd6pcQ_eGyKgbLdg4Wdc3CBFiqPywjY5XyVz7w=s240-c-k-c0x00ffffff-no-rj, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask .<4>, _NSURLErrorRelatedURLSessionTaskErrorKey=( "LocalDataTask .<4>" ), NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://yt3.ggpht.com/ytc/AMLnZu9uvd6pcQ_eGyKgbLdg4Wdc3CBFiqPywjY5XyVz7w=s240-c-k-c0x00ffffff-no-rj, NSUnderlyingError=0x60000321a250 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, _kCFNetworkCFStreamSSLErrorOriginalValue=-9816, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9816, _NSURLErrorNWPathKey=satisfied (Path is satisfied), interface: en0}}, _kCFStreamErrorCodeKey=-9816}


UPDATE 2: The problem is probably with encryption and secure connection, but so far i couldn't find a solution to fix it It should be probably something with info.plist

CodePudding user response:

Use this extension on UIImageView:

File - UIImageView Extension.swift
extension UIImageView {
 func download(from url: URL, contentMode mode: ContentMode = .scaleAspectFit) {
    contentMode = mode
    URLSession.shared.dataTask(with: url) { data, response, error in
        guard
            let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
            let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
            let data = data, error == nil,
            let image = UIImage(data: data)
            else { return }
        DispatchQueue.main.async() { [weak self] in
            self?.image = image
        }
    }.resume()
   }
 func downloadFromUrlString(from link: String, contentMode mode: ContentMode = .scaleAspectFit) {
    guard let url = URL(string: link) else { return }
    download(from: url, contentMode: mode)
 }
}

Now in view controller pass image url:

File - ViewController.swift
@IBOutlet weak var imageView: UIImageView!

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    imageView.downloadFromUrlString(from: "https://yt3.ggpht.com/ytc/AMLnZu-oDvWEJ-WfN9bgxQB2YAlnjC2uqN_c7JQZvX9Ikfg=s800-c-k-c0x00ffffff-no-rj", contentMode: .scaleToFill)
}

CodePudding user response:

Finally got it working

  1. Added this to my info.plist
<key>NSAppTransportSecurity</key>
  <dict>
      <key>NSExceptionDomains</key>
      <dict>
          <key>yt3.ggpht.com</key>
          <dict>
              <key>NSExceptionRequiresForwardSecrecy</key>
              <false/>
              <key>NSIncludesSubdomains</key>
              <true/>
              <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
              <true/>
              <key>NSTemporaryExceptionMinimumTLSVersion</key>
              <string>TLSv1.1</string>
          </dict>
      </dict>
  </dict>
  1. replaced https to http

    let channelImageUrl = pair.channelInfo.snippet.thumbnails.medium.url.replacingOccurrences(of: "https", with: "http")

  2. Combined it with answer of ameermuhammed

Result: Images are loading

result

  • Related