简体   繁体   中英

How to pass a String along with special characters and symbols into API using Swift?

I am new to swift programming,I have Implemented small application which can store title and small hint to remember some thing in daily life. when I passing string values along with symbols and special characters getting thread error I don't know how to pass, can anyone suggest me.I want to store any type of values .

below I have tried some codes

 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)

Just try like this,Remove replacingOccurrences

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

then you will get a two strings which automatically replaces the empty with %20, try with this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM