【问题标题】:How to pass a String along with special characters and symbols into API using Swift?如何使用 Swift 将字符串以及特殊字符和符号传递给 API?
【发布时间】:2018-08-31 15:37:27
【问题描述】:

我是快速编程的新手,我已经实现了一个小应用程序,可以存储标题和小提示以记住日常生活中的一些事情。当我传递字符串值以及符号和特殊字符时出现线程错误我不知道如何传递,谁能建议我。我想存储任何类型的值。

下面我尝试了一些代码

 let titleval = "My Coding"

            let desval = "<EXPR>:11:5: error: 'PostManager.Type' does not have a member named '$__lldb_wrapped_expr_3'"

            let  title = titleval.replacingOccurrences(of: " ", with: "%20")
            let  description1 = desval.replacingOccurrences(of: "\n", with: "%20")
            let  descriptionn : String = description1.replacingOccurrences(of: " ", with: "%20")
         print(descriptionn)
            var request = URLRequest(url: URL(string: "http://xx.xx.x.xx:xxxx/fsnotesvalueinsert?title=\(title)&userid=\(userid)&text=\(descriptionn)")!)
            print(request)


            request.httpMethod = "POST"

            let session = URLSession(configuration: .default)
            session.dataTask(with: request) {data, response, error in
                guard error == nil && data != nil else
                {
                    let alert = UIAlertController(title: "Check your Internet Connection", message: "", preferredStyle: .alert)

                    self.present(alert, animated: true, completion: nil)


                    let when = DispatchTime.now() + 3
                    DispatchQueue.main.asyncAfter(deadline: when){
                        // your code with delay
                        alert.dismiss(animated: true, completion: nil)
                    }
                    return
                }
                _ = NSString(data: data!, encoding: String.Encoding.ascii.rawValue)

【问题讨论】:

  • 而不是用 url justify 字符串替换特殊字符和空格,.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) URL(string: "xx.xx.x.xx:xxxx/…: .urlPathAllowed))
  • 在发送数据到服务器之前使用addingPercentEncoding
  • 对不起,你能详细说明一下这个 .addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) URL(string: "xx.xx.x.xx:xxxx/...: .urlPathAllowed))
  • 对于这一行 var request = URLRequest(url: URL(string: "xx.xx.x.xx:xxxx/…).getting thread error

标签: ios json swift string swift3


【解决方案1】:

就这样试试吧,去掉替换出现

let titleval = "Your code"
let escapedString = titleval.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
let  descriptionn = desval.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

然后你会得到一个自动用 %20 替换空的两个字符串,试试这个。

【讨论】:

    猜你喜欢
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    • 2012-09-07
    • 2017-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多