php - 如何通过php、swift将服务器上的图像显示到iOS设备

标签 php swift server uiimageview uiimage

我计划在我的 iPhone 上显示存储在服务器本地(macbook)上的图像以测试应用程序。图像存储在路径:/Applications/XAMPP/xamppfiles/imagestock。我用 PHP 编写网络服务来在浏览器上显示图像(如 URL),这里是服务器代码:

displayimage.php

<?php
$dir = '/Applications/XAMPP/xamppfiles/imagestock';
$file_display = array('jpg', 'jpeg', 'png', 'gif');

if (file_exists($dir) == false)
{
    echo 'Directory "', $dir, '" not found!';
}
else
{
    $dir_contents = scandir($dir);

    echo "<img src='img.php?name=photo-37.jpg' height='280' width='360' />";

}
?>

img.php

 <?php
    $name = $_GET['name'];
    $mimes = array
    (
        'jpg' => 'image/jpg',
        'jpeg' => 'image/jpg',
        'gif' => 'image/gif',
        'png' => 'image/png'
    );

    $ext = strtolower(end(explode('.', $name)));

    $file = '/Applications/XAMPP/xamppfiles/imagestock/'.$name;
    header('content-type: '. $mimes[$ext]);
    header('content-disposition: inline; filename="'.$name.'";');
    readfile($file);
?>

我只是测试并在浏览器上看到图像清晰,在我的客户端项目中在 UIImageView 上显示图像,我的代码在这里:

func load_image()
{

    let session = URLSession(configuration: URLSessionConfiguration.default)

    guard let url = URL(string: "http://192.168.1.2/MyWebService/api/displayimage.php") else { return }

    var request = URLRequest(url: url)
    request.httpMethod = "GET"

    session.dataTask(with: request) { (data, response, error) in

        if let error = error {
            print("Something went wrong: \(error)")
        }

        if let imageData = data {
            DispatchQueue.main.async {
                self.imageStock.image = UIImage(data: imageData)
            }
        }
        }.resume()
}

没有发生错误,但图像不显示。那么,我该如何解决这个问题呢?我尝试了一些方法,但没有成功。我认为服务器代码有错误?有人可以帮助我吗?

最佳答案

在您的 load_image() 函数中,您尝试从以数据形式提供图像的服务器加载图像。但是这种方法将在您每次调用该函数时尝试下载图像。 您应该在 load_image() 函数中仅获取图像的 URL。 然后使用 Kingfisher 第三方您应该显示图像。如下

let url = URL(string: "url_of_your_image") // e.g. url_of_your_image  = http://192.168.1.2/imagestock/img.png
imageView.kf.setImage(with: url)

它只会下载一次图像并自动保持冗余。 如何在代码中导入kingfisher,可以参见here

关于php - 如何通过php、swift将服务器上的图像显示到iOS设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50170077/

相关文章:

php - 为什么我从 MySQL 查询中得到重复项?

Swift mac 应用程序,在不知道路径的情况下运行终端命令(因此它会查看 $PATH 中的每个路径)?

php - Symfony 服务器日志级别/更详细?

不同格式的php搜索日期

php - 是否可以在不在服务器端使用任何脚本语言的情况下构建 cms?

ios - 帧突然改变而不是动画 [iOS]

java - 如何实现两个不同的服务器,由客户端使用相同的对象调用

java - 如何使用 Eclipse 在本地服务器上从 GitHub 运行 Web 应用程序?

PHP - 将数组作为字符串返回

ios - Swift 2 从 View Controller 返回选项卡栏 Controller 中的选定选项卡