TextureDownloadSample.cs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using BestHTTP;
  6. namespace BestHTTP.Examples.HTTP
  7. {
  8. public sealed class TextureDownloadSample : BestHTTP.Examples.Helpers.SampleBase
  9. {
  10. #pragma warning disable 0649
  11. [Header("Texture Download Example")]
  12. [Tooltip("The URL of the server that will serve the image resources")]
  13. [SerializeField]
  14. private string _path = "/images/Demo/";
  15. [Tooltip("The downloadable images")]
  16. [SerializeField]
  17. private string[] _imageNames = new string[9] { "One.png", "Two.png", "Three.png", "Four.png", "Five.png", "Six.png", "Seven.png", "Eight.png", "Nine.png" };
  18. [SerializeField]
  19. private RawImage[] _images = new RawImage[0];
  20. [SerializeField]
  21. private Text _maxConnectionPerServerLabel;
  22. [SerializeField]
  23. private Text _cacheLabel;
  24. #pragma warning restore
  25. private byte savedMaxConnectionPerServer;
  26. #if !BESTHTTP_DISABLE_CACHING
  27. private bool allDownloadedFromLocalCache;
  28. #endif
  29. private List<HTTPRequest> activeRequests = new List<HTTPRequest>();
  30. protected override void Start()
  31. {
  32. base.Start();
  33. this.savedMaxConnectionPerServer = HTTPManager.MaxConnectionPerServer;
  34. // Set a well observable value
  35. // This is how many concurrent requests can be made to a server
  36. HTTPManager.MaxConnectionPerServer = 1;
  37. this._maxConnectionPerServerLabel.text = HTTPManager.MaxConnectionPerServer.ToString();
  38. }
  39. void OnDestroy()
  40. {
  41. // Set back to its defualt value.
  42. HTTPManager.MaxConnectionPerServer = this.savedMaxConnectionPerServer;
  43. foreach (var request in this.activeRequests)
  44. request.Abort();
  45. this.activeRequests.Clear();
  46. }
  47. public void OnMaxConnectionPerServerChanged(float value)
  48. {
  49. HTTPManager.MaxConnectionPerServer = (byte)Mathf.RoundToInt(value);
  50. this._maxConnectionPerServerLabel.text = HTTPManager.MaxConnectionPerServer.ToString();
  51. }
  52. public void DownloadImages()
  53. {
  54. // Set these metadatas to its initial values
  55. #if !BESTHTTP_DISABLE_CACHING
  56. allDownloadedFromLocalCache = true;
  57. #endif
  58. for (int i = 0; i < _imageNames.Length; ++i)
  59. {
  60. // Set a blank placeholder texture, overriding previously downloaded texture
  61. this._images[i].texture = null;
  62. // Construct the request
  63. var request = new HTTPRequest(new Uri(this.sampleSelector.BaseURL + this._path + this._imageNames[i]), ImageDownloaded);
  64. // Set the Tag property, we can use it as a general storage bound to the request
  65. request.Tag = this._images[i];
  66. // Send out the request
  67. request.Send();
  68. this.activeRequests.Add(request);
  69. }
  70. this._cacheLabel.text = string.Empty;
  71. }
  72. /// <summary>
  73. /// Callback function of the image download http requests
  74. /// </summary>
  75. void ImageDownloaded(HTTPRequest req, HTTPResponse resp)
  76. {
  77. switch (req.State)
  78. {
  79. // The request finished without any problem.
  80. case HTTPRequestStates.Finished:
  81. if (resp.IsSuccess)
  82. {
  83. // The target RawImage reference is stored in the Tag property
  84. RawImage rawImage = req.Tag as RawImage;
  85. rawImage.texture = resp.DataAsTexture2D;
  86. #if !BESTHTTP_DISABLE_CACHING
  87. // Update the cache-info variable
  88. allDownloadedFromLocalCache = allDownloadedFromLocalCache && resp.IsFromCache;
  89. #endif
  90. }
  91. else
  92. {
  93. Debug.LogWarning(string.Format("Request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
  94. resp.StatusCode,
  95. resp.Message,
  96. resp.DataAsText));
  97. }
  98. break;
  99. // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
  100. case HTTPRequestStates.Error:
  101. Debug.LogError("Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception"));
  102. break;
  103. // The request aborted, initiated by the user.
  104. case HTTPRequestStates.Aborted:
  105. Debug.LogWarning("Request Aborted!");
  106. break;
  107. // Connecting to the server is timed out.
  108. case HTTPRequestStates.ConnectionTimedOut:
  109. Debug.LogError("Connection Timed Out!");
  110. break;
  111. // The request didn't finished in the given time.
  112. case HTTPRequestStates.TimedOut:
  113. Debug.LogError("Processing the request Timed Out!");
  114. break;
  115. }
  116. this.activeRequests.Remove(req);
  117. if (this.activeRequests.Count == 0)
  118. {
  119. #if !BESTHTTP_DISABLE_CACHING
  120. if (this.allDownloadedFromLocalCache)
  121. this._cacheLabel.text = "All images loaded from local cache!";
  122. else
  123. #endif
  124. this._cacheLabel.text = string.Empty;
  125. }
  126. }
  127. }
  128. }