Search code examples
jsonswiftswift3alamofireswifty-json

can not access the url inside of array , JSON response , using Alamofire & SwiftyJSON


Here is the JSON response I got from my URL

 {
 "message" : {
"8" : {
  "post_id" : 141,
  "post_img" : [
    {
      "guid" : "http:\/\/xxx\/wp-content\/uploads\/2016\/10\/IMG_1477452361.jpg"
    }
  ]
},
"2" : {
  "post_id" : 129,
  "post_img" : [
    {
      "guid" : "http:\/\/xxx\/wp-content\/uploads\/2016\/10\/IMG_1477280037.jpg"
    }
  ]
},
"9" : {
  "post_id" : 143,
  "post_img" : [
    {
      "guid" : "http:\/\/xxx\/wp-content\/uploads\/2016\/10\/IMG_1477453054.jpg"
    }
  ]
},
"3" : {
  "post_id" : 131,
  "post_img" : [
    {
      "guid" : "http:\/\/xxx\/wp-content\/uploads\/2016\/10\/IMG_1477282075.jpg"
    }
  ]
},
"user_posts" : "10",
"4" : {
  "post_id" : 133,
  "post_img" : [
    {
      "guid" : "http:\/\/xxx\/wp-content\/uploads\/2016\/10\/IMG_1477393524.jpg"
    }
  ]
},
"user_img" : "http:\/\/www.thewoodjoynt.com\/Content\/Images\/Products\/NoImageAvailable.jpg",
"user_id" : null,
"5" : {
  "post_id" : 135,
  "post_img" : [
    {
      "guid" : "http:\/\/xxx\/wp-content\/uploads\/2016\/10\/IMG_1477393867.jpg"
    }
  ]
},
"user_name" : null,
"6" : {
  "post_id" : 137,
  "post_img" : [
    {
      "guid" : "http:\/\/xxx\/wp-content\/uploads\/2016\/10\/IMG_1477393932.jpg"
    }
  ]
},
"7" : {
  "post_id" : 139,
  "post_img" : [
    {
      "guid" : "http:\/\/xxx\/wp-content\/uploads\/2016\/10\/IMG_1477395902.jpg"
    }
  ]
},
"following" : null,
"followers" : null,
"0" : {
  "post_id" : 110,
  "post_img" : [
    {
      "guid" : "http:\/\/xxx\/wp-content\/uploads\/2016\/10\/IMG_1475492476.jpg"
    }
  ]
},
"1" : {
  "post_id" : 112,
  "post_img" : [
    {
      "guid" : "http:\/\/xxx\/wp-content\/uploads\/2016\/10\/IMG_1475494067.jpg"
    }
     ]
},
"user_type" : false
 }
  }
  keys are &&&&&&&& ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
  fatal error: unexpectedly found nil while unwrapping an Optional value

I am using Alamofire 4 & SwiftyJSON to handle the JSON data, here is my function for fetching data and assigning it to a variable :

func getJSON(){

    let getEndPoint: String = "http://xxx/api/get_user_profile_info/"
    Alamofire.request(getEndPoint)
        .responseJSON { response in

            guard response.result.error == nil else {
                // got an error in getting the data, need to handle it
                print("error calling GET")
                print(response.result.error!)
                return
            }

            if let value = response.result.value {

                let json = JSON(value)
                print(json)

                if let dic = json["message"].dictionary {

                    //for Profile Image
                    if let userUrl = dic["user_img"]?.stringValue {
                        self.user_image = URL(string: userUrl)
                    }

                    //for collectionView Cell Image

                    //For getting only number keys with ascending order
                    let keys = (Array(dic.keys) as [String]).filter { (Int($0) != nil) }.sorted {
                        (s1, s2) -> Bool in return s1.localizedStandardCompare(s2) == .orderedAscending
                    }
                    print("keys are &&&&&&&&",keys)
                    //Loop through the keys Array and append all `post_image`.

                    for key in keys {
                        let post_imgAA = dic[key]?.array
                        for itemsIMG in post_imgAA! {
                            self.post_image = itemsIMG["guid"].URL
                        }
                    }

                    print("user_image are***********************************************")
                    print(self.user_image)

                    print("post_image are***********************************************")
                    print(self.post_image)

                     DispatchQueue.main.async {
                     self.afData = 1
                     self.collectionView.reloadData()
                     }

               }
           }
      }

here I am finding nil value in this loop

for key in keys {
                        let post_imgAA = dic[key]?.array
                        for itemsIMG in post_imgAA! {
                            self.post_image = itemsIMG["guid"].URL
                        }
                    }

Handling JSON data and converting it to foundation object is bit confusing for me, because I am pretty new in this. If any kind person could help it would be really helpful. Thank You in advance.


Solution

  • You are getting nil because key contains dictionary not Array, So change like this.

    for key in keys {
        if let innerDic = dic[key].dictionaryValue, 
           let post_imgAA = innerDic["post_img"].array {
            for itemsIMG in post_imgAA! {
                self.post_image = itemsIMG["guid"].URL
            }
        }
    }