R.AlAli R.AlAli - 1 year ago 96
JSON Question

SWIFT parsing images from JSON

In my application i want to parse JSON result that contains both text and images. the JSON result shows this string since the URL returned contains Arabic characters:

"Media_Photo" = " Ayach - \U0631\U0627\U0645\U064a \U0639\U064a\U0627\U0634/thumb/n583140_147657870534036_8903807944579055616.jpg";

This leads to error since it should be like: Ayach - رامي عياش/thumb/n583140_147657870534036_8903807944579055616.jpg

how can i change this URL and be able to present the images in the UIImageView.

i tried this code:

let mediaPhotoUrl = newsInGroup?.mediaPhotoURL
if let dataImageFornews = NSData(contentsOfURL: NSURL(string: (mediaPhotoUrl)!)!){
imageOfNews.image = UIImage(data: dataImageFornews)
} else {
imageOfNews.hidden = true

but an error occurred :

fatal error: unexpectedly found nil while unwrapping an Optional value

Also the JSON response returns:

"Media_Photo" = "<null>";

if no image. I handled this issue using this code:

if media.valueForKey("Media_Photo") != nil {
mediaPhoto = media.valueForKey("Media_Photo") as? String
print("mediaphotoURL: \(mediaPhoto)")

Is this the correct way?

print("mediaphotoURL: \(mediaPhoto)")


mediaphotoURL: Optional(" Ayach - رامي عياش/thumb/n583140_147657870534036_8903807944579055616.jpg")

Thank you in advance

Answer Source
  1. get a working json response, I could imagine that arabic characters are special characters, so have a look here Swift - encode URL

  2. This error occures, because you try to work with an nil value

    if let mediaPhotoUrlNotNil:String = mediaPhotoUrl {
     if let mediaPhotoUrlToNSURL = NSURL(string: mediaPhotoUrlNotNil) {
      if let dataImageFornews = NSData(contentsOfURL: mediaPhotoUrlToNSURL) {
           //not nil
          } else {
        } else {
         //its nil
       } else {
      //its nil
  3. Look here for a good way to get images from web: Swift - encode URL

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download