Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cyrillic symbols in URL

Tags:

ios

swift

nsurl

App crashes with following url:

let jsonUrl = "http://api.com/алматы/events"
let session = NSURLSession.sharedSession()
let shotsUrl = NSURL(string: jsonUrl)
let task = session.dataTaskWithURL(shotsUrl!)

Log:

fatal error: unexpectedly found nil while unwrapping an Optional value

It's because of cyrillic symbols in url. How can I solve this issue. Thanks for your help!

like image 344
aaisataev Avatar asked Feb 02 '16 08:02

aaisataev


1 Answers

Swift 4
Using String Extension Create a swift file named String+Extension.swift and paste this code

import UIKit
extension String{
    var encodeUrl : String
    {
        return self.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!
    }
    var decodeUrl : String
    {
        return self.removingPercentEncoding!
    }
}

and Use it like so: (sample according to question):

"http://api.com/алматы/events".encodeUrl
like image 108
Muhammad Asyraf Avatar answered Sep 29 '22 21:09

Muhammad Asyraf