2017-07-31 59 views
0

我无法将图像返回到tableView单元格。UIImage返回零从JSON请求到MySQL数据库的tableView细胞图像?

当我改变所有recipientImg参数字符串一切都正常运行,但是当我改变recipientImg参数的UIImage我得到(数据下载 致命错误:意外发现零而展开的可选值) (LLDB)

Ps我试图返回数据库中的文件路径作为图像。其他两个字符串作为字符串在tableView中返回,但我无法获取imageView以返回图像。

任何提示?

This is the JSON file on the server from the database 我也正在使用RecipientImg为[VARCHAR]在数据库

这里是viewermodel1.swift

import UIKit 

class viewedMeModel1: NSObject { 
//properties 

var username: String? 
var messageDetail: String? 
var recipientImg: UIImage? 
//empty constructor 

override init() 
{ 

} 

//construct with parameters 

init(username: String, messageDetail: String, recipientImg: UIImage)  { 

    self.username = username 
    self.messageDetail = messageDetail 
    self.recipientImg = recipientImg 
} 


//prints object's current state 


} 

这里是viewedMeModel2.swift

import UIKit 

protocol viewedMeModel2Protocol: class { 
func itemsDownloaded(items: NSArray) 
} 


class viewedMeModel2: NSObject { 
weak var delegate: viewedMeModel2Protocol! 

var data = Data() 

let urlPath: String = "http://" //this will be changed to the path where .php lives 

func downloadItems() { 

    let url: URL = URL(string: urlPath)! 
    let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default) 

    let task = defaultSession.dataTask(with: url) { (data, response, error) in 

     if error != nil { 
      print("Failed to download data") 
     }else { 
      print("Data downloaded") 
      self.parseJSON(data!) 
     } 

    } 

    task.resume() 
} 

func parseJSON(_ data:Data) { 

    var jsonResult = NSArray() 

    do{ 
     jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray 

    } catch let error as NSError { 
     print(error) 

    } 

    var jsonElement = NSDictionary() 
    let locations = NSMutableArray() 

    for i in 0 ..< jsonResult.count 
    { 

     jsonElement = jsonResult[i] as! NSDictionary 

     let location = viewedMeModel1() 

     //the following insures none of the JsonElement values are nil through optional binding 
     if let username = jsonElement["Username"] as? String, 
      let messageDetail = jsonElement["MessageDetail"] as? String, 
      let recipientImg = jsonElement["RecipientImg"] as? UIImage 

     { 

      location.username = username 
      location.messageDetail = messageDetail 
      location.recipientImg = recipientImg 

     } 

     locations.add(location) 

    } 

    DispatchQueue.main.async(execute: {() -> Void in 

     self.delegate.itemsDownloaded(items: locations) 

    }) 
} 

} 

这里is viewedMeController.swift import UIKit

class ViewerViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, viewedMeModel2Protocol { 


var feedItems: NSArray = NSArray() 
var selectedLocation : viewedMeModel1 = viewedMeModel1() 





@IBOutlet weak var viewedMe: UITableView! 

override func viewDidLoad() { 
    super.viewDidLoad() 
self.viewedMe.delegate = self 
    self.viewedMe.dataSource = self 

    let ViewedMeModel2 = viewedMeModel2() 
    ViewedMeModel2.delegate = self 
    ViewedMeModel2.downloadItems() 
    // Do any additional setup after loading the view. 
} 

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

func itemsDownloaded(items: NSArray) { 

    feedItems = items 
    self.viewedMe.reloadData() 

} 

func numberOfSections(in tableView: UITableView) -> Int { 
    return feedItems.count 
} 

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    // Return the number of feed items 
    return feedItems.count 

} 



func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    // Retrieve cell 
    let cellIdentifier: String = "basicCell" 
    let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)! 
    // Get the location to be shown 
    let item: viewedMeModel1 = feedItems[indexPath.row] as! viewedMeModel1 

    // Get references to labels of cell 
    cell.UIImage?.image = item.recipientImg! 
    return cell 
} 
+0

和一个队友的话,你的命名约定是非常糟糕的,你应该总是使用大写的名称类和协议,以及骆驼套管的变量名。 –

回答

1

问题是与你的viewedMeModel2.swift,在这一行:

let recipientImg = jsonElement["RecipientImg"] as? UIImage 

条件展开的结果总是支持返回recipientImg =零,因为jsonElement [ “RecipientImg”]是字符串,它不能被转换成UIImage。 你应该重写代码,以这样的:

if let username = jsonElement["Username"] as? String, 
     let messageDetail = jsonElement["MessageDetail"] as? String, 
     let recipientImgString = jsonElement["RecipientImg"] as? String 

    { 

     location.username = username 
     location.messageDetail = messageDetail 
     location.recipientImg = UIImage(named: recipientImgString) 
    } 
+0

这是非常正确的,但我很确定UIImage(named:String)初始值设定项仅用于存储在应用程序主包中的图像。 (您在本地存储在图像资产文件夹中的图像) – user3353890

+0

您说得对,我只是假设PO由于其示例json的内容而将图像存储在他的图像资产中。是的,我的UIImage(name :)可能是错误的:) –

+0

不用担心!你可能是正确的,他在本地存储它们。只是想指出,如果他不是,就这样! :) – user3353890

1

我的猜测是,jsonElement["RecipientImg"]返回一个String不是UIImage,所以你要nil,因为你不能投的字符串作为图像。尝试从jsonElement["RecipientImg"]获取图片网址,然后从该网址创建UIImage。事情是这样的:

let imageURL = jsonElement["RecipientImg"] as? String 
let myImage = UIImage(contentsOfFile: imageURL) 

您还可以使用的UIImage初始化init?(data: Data)如果你得到某种形式的数据对象。

同样,jsonElement["RecipientImg"]的对象可能不能转换为UIImage,我的猜测是它是String。了解它是什么以及可以将它转换为什么,然后从文档中使用适当的UIImage初始值设定项。

https://developer.apple.com/documentation/uikit/uiimage