在Swift 3的tableview中下载并显示URL中的图像

时间:2017-04-14 20:03:30

标签: ios swift

我目前正在尝试为显示图像以及其他信息的应用程序设计新闻源。我可以从我们的mySQL数据库中获取URL,但是当我尝试下载它时,我收到一条错误,说“致命错误:在展开可选值时意外发现nil”,尽管提供了这段代码:

                if let imageData = data {
                    let pic = UIImage(data: imageData)
                    print()
                    cell.activityImage.image = pic
                    self.images.append(pic!)
                }

非可选字符串。这是整个代码

 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]

    //print(post["path"])


    //let image = images[indexPath.row]
    let imaged = post["path"] as! String
    //print(imaged)

    let image = URL(string: imaged)! //download url
    print(image)

    let username = post["username"] as? String
    let text = post["text"] as? String

    let session = URLSession(configuration: .default)
    let downloadPicTask = session.dataTask(with: image) {
        (data, response, error) in
        if let e = error {
            print("Error downloading image: \(e)")
        } else {
            if (response as? HTTPURLResponse) != nil {
                if let imageData = data {
                    let pic = UIImage(data: imageData)
                    print()
                    cell.activityImage.image = pic
                    self.images.append(pic!)
                } else{
                    print("couldn't get image: image is nil")
                }
            } else {
                print("Couldn't get response code")
            }

        }
    }
    cell.titleLabel.text = text
    cell.usernameLabel.text = username


    downloadPicTask.resume()
    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

                    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 self.activities.indices {

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

                     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)
                                        print(self.images)
                                }
                        }
                     }

                     /*
                     if path != "" {
                     //let url = URL(string: path!)!
                     let url = URL(fileURLWithPath: path!)
                     let imageData = try? Data(contentsOf: url)
                     //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!)

     }

 }

如果您有任何建议,请告诉我们!

0 个答案:

没有答案