Image path not convert to url in swift3

2019-06-14 17:09发布

I have post response i want to download image from image_path

let fileUrl = NSURL(fileURLWithPath: (posts.value(forKey: "image_path") as! [String])[indexPath.row])
        print(fileUrl as Any) // here i can get path

        if FileManager.default.fileExists(atPath: (fileUrl)// nil value {
            let url = NSURL(string: (posts.value(forKey: "image_path") as! [String])[indexPath.row]) // Here url found nil
            let data = NSData(contentsOf: url! as URL)
            cell.LocationImage?.image = UIImage(data: data! as Data)
        }

UPDATE:

[1]: https://i.stack.imgur.com/KWCS9.png

1条回答
时光不老,我们不散
2楼-- · 2019-06-14 17:53

That URL is not a local file path URL, nor a valid URL accoridng to my browser.

The URL you have provided above returns a server error in the browser and does not return an image. See screenshot

Screenshot

You would need to ensure that the image is accessible and the URL actually returns an image response firstly. Then you would need to download the image. Not sure if you are using any libraries or not so I will post an example without.

//: Playground - noun: a place where people can play

import UIKit
import XCPlayground
import PlaygroundSupport

let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))

// random image from images.google.com
let urlString = "https://files.allaboutbirds.net/wp-content/uploads/2015/06/prow-featured-240x135.jpg"

let url = URL(string: urlString)
let session = URLSession.shared

let task = session.dataTask(with: url!) { data, response, error in
    guard error == nil else {
        print("[ERROR] - Failed to download image")
        return
    }

    if let data = data {
        let image = UIImage(data: data)
        DispatchQueue.main.async {
            imageView.image = image
        }
    }
}

let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
view.addSubview(imageView)

task.resume()
PlaygroundPage.current.liveView = view

UPDATE:

Screenshot 2

查看更多
登录 后发表回答