URL字符问题



我对URL的角色有问题,这是我的代码;

我的功能;

func getMahalle (addres: String){
    let urlString = adres
    let url = URL(string: urlString)// I'm getting error right after this line when have urlString ı,İ,ş,Ş,ü,Ü,ç,Ç,ğ,Ğ,ö,Ç , url = nil after this line
    let task = URLSession.shared.dataTask(with: url!) { (data,urlresponse, error) in
        if error != nil {
            print(error!)
        }
        else {
            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
                if let table = json["Table"] {
                    for var i in 0..<(table as AnyObject).count {
                        let tableDict = (table as! Array<AnyObject>) [i] as! [String: Any]
                        let iller = tableDict["site_mahalle"]
                        self.mahallelerDizi.append(iller as! String)
                                                    DispatchQueue.main.async {
                            self.pickerView.reloadAllComponents()
                        }
                    }
                }
            }
            catch {
            }
        }
    }
    task.resume() }

呼叫;

getMahalle(addres: "http://alfa.reelim.com/ReelService.asmx/getMahalle?ilce=nilüfer") 

错误是:致命错误:未包装可选值

时出乎意料地发现了无效

i m不明白为什么url = nil。

添加百分比编码应完成工作:

let urlString = adres.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlFragmentAllowed)
let url = URL(string: urlString!) // Take care of forced wrapping
// Here this url: http://alfa.reelim.com/ReelService.asmx/getMahalle?ilce=Ö
// will become this: http://alfa.reelim.com/ReelService.asmx/getMahalle?ilce=%C3%96
let task = URLSession.shared.dataTask(with: url!) // Take care of forced wrapping
{ 
   (data,urlresponse, error) in
    // parsing here
}

doc的零件:

重要 您不能在已经已经存在的字符串上调用此方法 编码百分比。在已经已经存在的字符串上调用此方法 编码百分比会导致字符的百分比为一个百分比 序列为两次分配的序列。

和:

返回值返回编码的字符串,或nil如果转换 不可能

override func viewDidLoad() {
    super.viewDidLoad()

let secilenIlce = UserDefaults.standard.object(forKey: "secilenIlce") as? NSString
    if let yansiyan = secilenIlce {
        degerMahalle = yansiyan as String
    } mahalleCek(adres: "http://alfa.reelim.com/ReelService.asmx/getMahalle?ilce=(degerMahalle)")}

逃脱不支持的字符:

guard let escaped = urlString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed),
      let url = URL(string: escaped)
    else {
        fatalError("Better handle the error")
}

相关内容

  • 没有找到相关文章