从文档目录获取图像而不是文件路径Swift 3

时间:2017-09-05 01:52:01

标签: swift swift3 xcode8 nsdocumentdirectory

这是我保存图像的方式

$csv_path

下面是我用来检索图片的代码,但我得到的是URL而不是图像文件来填充tableview。任何帮助将不胜感激

namespace App\Providers;

use Illuminate\Support\Arr;
use Storage;
use League\Flysystem\Filesystem;
use Aws\S3\S3Client;
use League\Flysystem\AwsS3v3\AwsS3Adapter as S3Adapter;
use Illuminate\Support\ServiceProvider;

class CustomS3Filesystem extends ServiceProvider
{

    /**
     * Format the given S3 configuration with the default options.
     *
     * @param  array  $config
     * @return array
     */
    protected function formatS3Config(array $config)
    {
        $config += ['version' => 'latest'];

        if ($config['key'] && $config['secret']) {
            $config['credentials'] = Arr::only($config, ['key', 'secret']);
        }

        return $config;
    }

    /**
     * Bootstrap a custom filesystem
     *
     * @return void
     */
    public function boot()
    {
        Storage::extend('s3_custom', function($app, $config)
        {
            $s3Config = $this->formatS3Config($config);
            return new Filesystem(
                new S3Adapter(
                    new S3Client($s3Config),
                    $config['bucket'],
                    null,
                    [
                        'CacheControl'  => 'max-age=432000'
                    ]
                )
            );
        });
    }

    public function register()
    {
        //
    }
}

2 个答案:

答案 0 :(得分:4)

这只是因为您的图片名称无效。使用调试器查找imageUrl的确切值,我打赌它类似于.../Documents/img。你想要的更像是.../Documents/Sep-04-2017-12.img

您必须在视图控制器中存储currentFileName,以便日后可以参考。

此外,您的命名策略非常脆弱。许多图像最终都可以共享一个名称。

如果您有一个装满图片的文件夹,您可以迭代该文件夹以取回img个文件:

let fileManager = FileManager.default
let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
let directoryContents = try! fileManager.contentsOfDirectory(at: documentDirectory, includingPropertiesForKeys: nil)
for imageURL in directoryContents where imageURL.pathExtension == "img" {
    if let image = UIImage(contentsOfFile; imageURL.path) {
        // now do something with your image
    } else {
       fatalError("Can't create image from file \(imageURL)")
    }
}

答案 1 :(得分:0)

尝试使用此

 func getImage(){
        let fileManager = FileManager.default
        let imagePAth = (self.getDirectoryPath() as NSString).appendingPathComponent("apple.jpg") // saved image name apple.jpg
        if fileManager.fileExists(atPath: imagePAth){
            self.lockbackImageview.image = UIImage(contentsOfFile: imagePAth)
        }else{
            print("No Image")
            self.lockbackImageview.image = UIImage.init(named: "1.jpg")
        }
    }