我计划在我的 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/