Ios 下载的Json包含空值和应用程序崩溃

Ios 下载的Json包含空值和应用程序崩溃,ios,swift3,Ios,Swift3,我正在开发一个应用程序,其中数据以JSON格式从服务器下载。但若图像值为nill,那个么应用程序就会崩溃。我还设置了一个默认图片,但光标并没有进入else语句。请指导我如何正确完成任务。这是我的密码 func downloadUsersData(){ let email = UserDefaults.standard.value(forKey: "userEmail") var urlString = "http://nexusvision.net/zeroone/selec

我正在开发一个应用程序,其中数据以JSON格式从服务器下载。但若图像值为nill,那个么应用程序就会崩溃。我还设置了一个默认图片,但光标并没有进入else语句。请指导我如何正确完成任务。这是我的密码

func downloadUsersData(){

    let email = UserDefaults.standard.value(forKey: "userEmail")

    var urlString = "http://nexusvision.net/zeroone/selectuserbasic.php"
    urlString.append("?")
    urlString.append("id=\(email!)")

    print("This is URL : \(urlString)")

    let url = URL(string: urlString)
    var request = URLRequest(url: url!)

    request.httpMethod = "GET"

    let task = URLSession.shared.dataTask(with: request) { data, response, error in

        if error != nil{
            print(error?.localizedDescription)

        }

        let data = data

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }

        let responseString = String(data: data!, encoding: .utf8)
        print("all Countary responseString = \(responseString)")

        let responseData = responseString


        do {

            let jsonValue = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSDictionary

            print("This is Json : \(jsonValue.value(forKey: "product"))")

            if let profile = jsonValue.value(forKey: "product") as? NSArray
            {
                for profileData in profile{

                    if let dict = profileData as? NSDictionary{

                        if let firstName = dict.value(forKey: "firstname"){

                            print("Name is : \(firstName)")

                            self.defaults.set(firstName, forKey: "firstName")
                        }

                        if let lastName = dict.value(forKey: "lastname"){

                            print("Last Name : \(lastName)")
                            self.defaults.set(lastName, forKey: "lastName")

                        }

                        if let imageData = dict.value(forKey: "picture")    {

                            print("This is Image Json: \(imageData)")


                            let convertToImage = imageData

                            let decodedData : NSData = NSData(base64Encoded: convertToImage as! String, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters)!

                            let decodedimage: UIImage = UIImage(data: decodedData as Data)!


                            print("Thats Decoded : \(decodedimage)")

                            self.profilePicImageShow.image = decodedimage

                        }

                        else{

                            self.profilePicImageShow.image = UIImage(named: "Empty")
                        }

                    }
                }
            }
        }
        catch let error as NSError {
            print(error)
        }
        }.resume()
}
从技术上讲,键“picture”不是nil,根据JSON响应,它是空字符串。因此,当您执行代码时,它将进入if语句并最终在
让decodedimage:UIImage=UIImage(数据:decodedData作为数据)as
decodedData
为零

回答: 修改if语句,如下所示

if let imageData = dict.value(forKey: "picture"), (imageData as! String) != ""   {
这将解决您的崩溃问题。

更换

if let imageData = dict.value(forKey: "picture") {
    print("This is Image Json: \(imageData)")
    let convertToImage = imageData
    let decodedData : NSData = NSData(base64Encoded: convertToImage as! String, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters)!
    let decodedimage: UIImage = UIImage(data: decodedData as Data)!
    print("Thats Decoded : \(decodedimage)")
    self.profilePicImageShow.image = decodedimage
} else {
    self.profilePicImageShow.image = UIImage(named: "Empty")
}


另外,确保键“picture”实际上包含nil

您可以添加
guard
语句,如下所示:

guard let decodedData = NSData(base64Encoded: convertToImage as! String, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters) else {
   return
}


guard let decodedimage: UIImage = UIImage(data: decodedData as Data) else {
   return
}
由于您正在强制展开,如果无法从数据创建图像,您的应用程序将崩溃


作为补充说明,您可以使用和,这些都是非常好的libs来处理
HTTP
请求。

在我的例子中,我将从JSON获取URL,然后下载带有URL的图像;所以,若url为零,那个么我将添加虚拟图像,否则我将从url下载图像。这是我的东西:

var news = respone.result.value as! Dictionary<String,Any>
if let result:NSArray = news["stories"] as? NSArray
{
    for i in 0..<result.count
    {
        let str = (((result[i] as! NSDictionary).value(forKey: "ximg") as! NSDictionary).value(forKey: "ipath") as? String)

        if str == nil
        {
            self.news_url.append("nil")
        }
        else
        {
            self.news_url.append(str!)
        }
    }
}
self.tableview.reloadData()
var news=respone.result.value as!字典
如果让结果:NSArray=news[“stories”]as?不可变数组
{

对于0中的i.。每次你说
都意味着崩溃。你说了8次。你会对崩溃感到惊讶吗?不要强制展开选项,除非你100%确定它们包含值。如果JSON包含null值,我想使用else语句。如果我使用?而不是!,那么Xcode说set?to!。当我使用它时,会显示错误与此类似,无法将类型为“NSNull”(0x102bf8918)的值强制转换为“NSString”(0x101a7ec60)。此图片作为Base64下载,然后解码
var news = respone.result.value as! Dictionary<String,Any>
if let result:NSArray = news["stories"] as? NSArray
{
    for i in 0..<result.count
    {
        let str = (((result[i] as! NSDictionary).value(forKey: "ximg") as! NSDictionary).value(forKey: "ipath") as? String)

        if str == nil
        {
            self.news_url.append("nil")
        }
        else
        {
            self.news_url.append(str!)
        }
    }
}
self.tableview.reloadData()