替换URL中出现的空格

2020/12/12 05:22 · ios ·  · 0评论

我在iPhone应用程序中有一个可以使用的URL。但是问题在于URL中有一些空格。我想用'%20'替换空格。我知道有stringByReplacingOccurencesOfStringstringByAddingPercentEscapesUsingEncoding方法。我也用过它们。但是他们没有为我工作。空格被一些异常值代替。

我正在将这些方法应用于的实例NSString

替换url中的空格的正确格式为:

迅捷4.2,迅捷5

var urlString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

斯威夫特4

var urlString = originalString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)

目标C

NSString *urlString;//your url string.

urlString = [originalUrl stringByReplacingOccurrencesOfString:@" " withString:@"%20"];

要么

urlString = [originalUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

iOS 9及更高版本

urlString = [originalUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

斯威夫特2.0

let originalUrl = "http://myurl.com/my photo.png"
let urlNew:String = urlReq.stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLQueryAllowedCharacterSet())! 

输出:

http://myurl.com/my%20photo.png

要替换SWIFT 3中的出现

let updatedUrl = originalUrl.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)

斯威夫特4

用replaceOccurrences方法替换空白空间的另一种方法:

let yourString = "http://myurl.com/my photo.png"
let urlNew:String = yourString.replacingOccurrences(of: " ", with: "%20").trimmed 

这将用'%20'替换空白(“”)

迅捷5

var urlString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

Swift 5.3,清理字符串空间,

let str = "  www.test.com  "
let trimmed = str.trimmingCharacters(in: .whitespacesAndNewlines)
print(str) // "www.test.com" 
var urlString :String = originalUrl.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!

希望这会起作用

let url = "https:youtube.56432fgrtxcvfname=xyz&sname=tuv"
let urlNew:String = url.replacingOccurrences(of: " ", with: "%20")
Alamofire.request(urlNew, method: .get, headers: headers).responseJSON{
response in
print(response)    
}

它将删除网址中的所有空格。

SWIFT 3.1

用replaceOccurrences替换空白空间的简单方法:

URL = URL.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)

Swift 4,iOS-9

let **urlSearchVal**:String = "top 10 movies"     
let urlString = 

    "https://www.googleapis.com/youtube/v3/search?part=snippet&q=\(urlSearchVal)&key=......&type=video"   
//replace ...... above with your youtube key   
// to ignoring white space in search  
        let UrlString :String = urlString.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!

Swift 4解决方案。您只需传递一个字符串,它就会用%20填充空格,并在字符串的开头添加“ http://”。太甜了!

URL(fileURLWithPath: String) 
本文地址:http://ios.askforanswer.com/tihuanurlzhongchuxiandekongge.html
文章标签: ,   ,   ,  
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!