ios - 如何从 URL Swift 下载图像

标签 ios xcode swift swift2

所以我尝试从 url 链接下载图像,然后尝试将它们添加到已下载图像的数组中,但遇到了麻烦。

我已经搜索了 stackoverflow 和相关网站,但找不到类似的问题。

我正在下载两种图像。

第一种类型的例子是:http://img.youtube.com/vi/7lC3UZtLa6Y/0.jpg

第二种类型的例子是:http://master.dextra.xyz/_uploads/photos/image_111.webp

请点击两者查看区别

我下载第一种没有问题,只需使用以下代码即可。但是正如您所看到的,第二个 url 链接会在单击时自行下载,因此在提取它时我得到 nil

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {

 // Downloading image 1
            let data = NSData(contentsOfURL: NSURL(string: "http://img.youtube.com/vi/7lC3UZtLa6Y/0.jpg")!)
            self.downloadedImages.append(UIImage(data: data!)!)
// No problem downloading above image, also shows up in my app

      // Downloading image 2
        let data = NSData(contentsOfURL: NSURL(string: "http://master.dextra.xyz/_uploads/photos/image_111.webp")!)
            self.downloadedImages.append(UIImage(data: data!)!)
        // getting nil in UIImage(data: data!), although it says that data is around 300000 bytes.

        dispatch_async(dispatch_get_main_queue(), {
        // Updating UI
       });
    }

那么,如何下载第二类图片呢?它下载成功。但是无法访问它,因为它存储在某处的计算机中,但我不确定

如有任何帮助,我们将不胜感激。谢谢

最佳答案

我试过你的代码。第二种情况下图片下载成功。您得到 nil 而不是有效 UIImage 的原因是图像格式不受支持。以下是支持的格式列表:

标记图像文件格式 (TIFF)

联合图像专家组 (JPEG)

图形交换格式 (GIF)

可移植网络图形 (PNG)

Windows 位图格式 (DIB)

Windows 图标格式 (.ico)

Windows 光标 (.cur)

XWindow 位图 (.xbm)

https://developer.apple.com/library/ios/documentation/2DDrawing/Conceptual/DrawingPrintingiOS/LoadingImages/LoadingImages.html#//apple_ref/doc/uid/TP40010156-CH17-SW7

希望对您有所帮助。

关于ios - 如何从 URL Swift 下载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37606882/

相关文章:

ios - 运行异步生成的代码块, 'only' 当特定 View Controller 可见并受控制时

ios - Azure 查询在不应进行 iOS7 编程时返回所有行

ios - xcode项目中可执行文件的扩展名是什么

ios - 在 Xcode 中调试静态库

xcode - 过期的企业分发配置文件无法续订

swift - Collection View 存储按钮按下 Swift

android - React Native - Dimensions.set() 不起作用?

ios - UISearch 栏不调用 searchBarTextDidBeginEditing

swift - 持有弱引用是否可以防止保留循环被视为泄漏?

ios - 从 (_,_,_) 类型的抛出函数 throws -> Void 到非抛出函数类型 (NSData?, NSURLResponse?, NSError?) -> Void 的无效转换