Swift 3 - 从mySQL数据库中提取图像

时间:2017-04-02 21:32:30

标签: php ios mysql json swift

我目前正在设计一个有新闻源的应用程序。图像和文本存储在我们的数据库中,但是我无法拉动图像并显示它。我的代码应该可以工作,但我得到一个致命的错误,说“THREAD 1:EXC_BAD_INSTRUCTION”

let imageData = try? Data(contentsOf: url)
let image = UIImage(data: imageData!)!

并且编译器显示此消息 - “致命错误:在解包可选值时意外发现nil”。

我在这段代码中收到错误:

if!path!.isEmpty {
    let url = URL(string: path!)!
    let imageData = try? Data(contentsOf: url)
    let image = UIImage(data: imageData!)!
    self.images.append(image)
} else {
    let image = UIImage()
    self.images.append(image)
}

作为编程的新手,我已经坚持了很长一段时间了。如果您有任何建议,请告诉我!谢谢!

另外,我试图检索的照片是.jpg,不确定这是否很重要。

(如果需要,这是代码的其余部分)

import UIKit

class SecondViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var activities = [AnyObject]()
var images = [UIImage]()

@IBOutlet var tableView: UITableView!


override func viewDidLoad() {
    super.viewDidLoad()

    //tableView.contentInset = UIEdgeInsetsMake(2, 0, 0, 0)


}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return activities.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "activity", for: indexPath) as! CustomCell

    let post = activities[indexPath.row]
    let image = images[indexPath.row]
    let username = post["username"] as? String
    let text = post["text"] as? String

    cell.titleLbl.text = text
    cell.userLbl.text = username
    cell.activityImage.image! = image
    //cell.dateLbl.text = activities[indexPath.row]
    //cell.activityImage.image = images[indexPath.row]


    return cell
}

override func viewWillAppear(_ animated: Bool) {
    loadActivities()
}


func loadActivities() {
    let id = user!["id"] as! String
    let url = URL(string: "https://cgi.soic.indiana.edu/~team7/posts.php")!

    var request = URLRequest(url: url)

    request.httpMethod = "POST"

    let body = "id=\(id)&text=&uuid="
    request.httpBody = body.data(using: String.Encoding.utf8)

    URLSession.shared.dataTask(with: request) { data, response, error in
        DispatchQueue.main.async(execute: {

            if error == nil {

                do {

                    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

                    // clean up
                    self.activities.removeAll(keepingCapacity: false)
                    self.images.removeAll(keepingCapacity: false)
                    self.tableView.reloadData()

                    guard let parseJSON = json else {
                        print("Error while parsing")
                        return
                    }

                    guard let posts = parseJSON["posts"] as? [AnyObject] else {
                        print("Error while parseJSONing")
                        return
                    }


                    self.activities = posts

                    for i in 0 ..< self.activities.count {

                        let path = self.activities[i]["path"] as? String

                        if !path!.isEmpty {
                            let url = URL(string: path!)!
                            let imageData = try? Data(contentsOf: url)
                            let image = UIImage(data: imageData!)!
                            self.images.append(image)
                        } else {
                            let image = UIImage()
                            self.images.append(image)
                        }

                    }



                    self.tableView.reloadData()


                } catch {
                }

            } else {
            }

        })

        }.resume()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

extension NSMutableData {

func appendString(_ string : String) {

    let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
    append(data!)

}

}

2 个答案:

答案 0 :(得分:0)

你可以尝试这样的事情来避免运行时错误:

if let actualPath = path, !actualPath.isEmpty, let url = URL(string: actualPath) {
    if let imageData = try? Data(contentsOf: url) {
        if let image = UIImage(data: imageData) {
            self.images.append(image)
        }
    }
}

而不是

if!path!.isEmpty {
    let url = URL(string: path!)!
    let imageData = try? Data(contentsOf: url)
    let image = UIImage(data: imageData!)!
    self.images.append(image)
}

答案 1 :(得分:-1)

你为什么这样做?从服务器获取映像的URL,然后使用SDWebImage在cellForRowAtIndexPath中异步加载它们。这是一个图书馆,你可以在这里找到它。 https://github.com/rs/SDWebImage。这样您就不需要将图像存储在数组中,加载速度会更快。

或者您也可以实现自己的异步图像加载。