0

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" = "http://95.138.143.176/photos/FB/Ramy Ayach - \U0631\U0627\U0645\U064a \U0639\U064a\U0627\U0634/thumb/n583140_147657870534036_8903807944579055616.jpg";

This leads to error since it should be like:

http://95.138.143.176/photos/FB/Ramy 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)")

gives

 mediaphotoURL: Optional("http://95.138.143.176/photos/FB/Ramy Ayach - رامي عياش/thumb/n583140_147657870534036_8903807944579055616.jpg")

Thank you in advance

R.AlAli
  • 85
  • 2
  • 10

1 Answers1

0
  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 {
           //nil
          }
        } else {
         //its nil
        }
       } else {
      //its nil
     }
    
  3. Look here for a good way to get images from web: Swift - encode URL

Community
  • 1
  • 1
kuzdu
  • 7,124
  • 1
  • 51
  • 69