下载的Json包含Null值和应用程序Crash ios swift

时间:2017-05-04 03:30:48

标签: ios swift3

我正在使用一个应用程序,其中数据以JSON格式从服务器下载。但如果Image值为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()
}

4 个答案:

答案 0 :(得分:0)

技术上,关键"图片"不是nil,根据JSON响应它的空字符串。因此,当您执行代码时,它将进入if语句并最终崩溃 let decodedimage: UIImage = UIImage(data: decodedData as Data)!decodedData为零。

<强>答案: 修改你的if语句如下

if let imageData = dict.value(forKey: "picture"), (imageData as! String) != ""   {

这可以解决您的崩溃问题。

答案 1 :(得分:0)

替换

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")
}

let imageData = dict["picture"] as? NSData ?? UIImageJPEGRepresentation(UIImage(named: "Empty")!, 1.0)
self.profilePicImageShow.image = UIImage(data: imageData!)

另外,请确保密钥&#34;图片&#34;实际上包含nil

答案 2 :(得分:0)

您可以添加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
}

由于您要强行解包,如果无法从数据创建图像,您的应用就会崩溃。

作为旁注,您可以使用thisthis,这些是非常好的库,可以使用HTTP请求。

答案 3 :(得分:0)

在我的情况下,我将从JSON获取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()