Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to Load an Image from URL with Special Characters in iOS Swift3

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 1.47k
    Comment on it

    Swift#3
    If an image URL contains special character which doesn't load image on image view then we need to do more than UTF8 encoding. We usually decode string using Unicode methods but sometimes it is not sufficient to encode special character.

     


    For an instance lets take below URL as an example here.

    let imgURL = "http://www.example.fr/wp-content/uploads/2014/06/préliminaire.jpg"

     

    Now, we will encode the image imgURL using basic String encoding.

    let cString = imgURL.cString(using: String.Encoding.utf8)
    let encodedStr = NSString(bytes: ((cString))!, length: ((cString?.count))!, encoding: String.Encoding.utf8.rawValue)!

    Above code line will returns an encoded String but now we need String with the characters in Unicode General Category.

    So we will use use below code to achieve it.

    let controlCharStr = NSString(format: "%@", encodedStr.trimmingCharacters(in: CharacterSet.controlCharacters))

     

    Now finally we need a character set containing the characters allowed in an URL's fragment component.

    let urlStr = controlCharStr.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlFragmentAllowed)

     

    Now you can finally load image on your image view. I' m using AFNetwork class to load image on image view.

    yourImageView.af_setImage(withURL: URL.init(string: urlStr!)!)

    Hope this will work for you. For any questions, please feel free to ask in comments.
    Happy Coding !!!

     

     

    How to Load an Image from URL with Special Characters in iOS Swift3

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: