替换 URL 中出现的空格

发布于 2024-09-13 16:27:50 字数 228 浏览 18 评论 0原文

我在 iPhone 应用程序中有一个可以使用的 URL。但问题是它的 URL 中有一些空格。我想用“%20”替换空格。我知道有 stringByReplacingOccurencesOfString 和 stringByAddingPercentEscapesUsingEncoding 方法。我也用过它们。但他们不为我工作。空格被一些不寻常的值替换。

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

I have a URL in an iPhone application to work with. But the problem is that it has some spaces in the URL. I want to replace the spaces with '%20'. I know that there are the stringByReplacingOccurencesOfString and stringByAddingPercentEscapesUsingEncoding methods. I also have used them. But they are not working for me. The spaces are replaced by some unusual values.

I'm applying those methods on an instance of NSString.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

爱要勇敢去追 2024-09-20 16:27:50

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

Swift 4.2 、 Swift 5

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

Swift 4

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

Objective C

NSString *urlString;//your url string.

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

urlString = [originalUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

iOS 9 及更高版本

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

The correct format for replacing space from url is :

Swift 4.2 , Swift 5

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

Swift 4

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

Objective C

NSString *urlString;//your url string.

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

or

urlString = [originalUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

iOS 9 and later

urlString = [originalUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
溺ぐ爱和你が 2024-09-20 16:27:50

Swift 2.0

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

输出:

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

Swift 2.0

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

Output:

http://myurl.com/my%20photo.png
与酒说心事 2024-09-20 16:27:50

要替换 SWIFT 3 中的出现:

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

To replace occurence in SWIFT 3 :

let updatedUrl = originalUrl.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
淡淡绿茶香 2024-09-20 16:27:50

Swift 4

使用 replacementOccurrences 方法替换空白的另一种方法:

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

这会将空白 (" ") 替换为 '%20'

Swift 4

Another way to replace an empty space with replacingOccurrences method:

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

That will replace the empty space (" ") with '%20'

Oo萌小芽oO 2024-09-20 16:27:50

雨燕5

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

Swift 5

var urlString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
风向决定发型 2024-09-20 16:27:50

最快的解决方案:只需使用 stringy 方法...

.replacingOccurrences(of: " ", with: "%20")

...在字符串末尾,它就会按照它说的那样进行。

Apple 应该感到尴尬的是,他们的 URL(string: ) 方法不会自动执行此操作(以及更多操作)。现在是 2023 年,我浪费了 3 个小时来找到这个半途而废的解决方案。

我的具体示例是在 cellForItemAt 内部并且与选项有关。

let stringOfImageURLFromFirebase = wordController?.word?.images[indexPath.item].imgUrl

let stringWithNoSpaces = string?.replacingOccurrences(of: " ", with: "%20")

if let imageURLString = stringWithNoSpaces,
   let imageURL = URL(string: imageURLString) {
         cell.definitionImageView.loadImageFromFirebase(url: imageURL)
    } else {
        cell.definitionImageView.image = UIImage(named: "slictionarylogo")
    }

你可以长时间摆弄 .addingPercentEncoding,尝试 NSURL 废话,使用显而易见的东西你会更快。苹果很糟糕,而且应该让这个问题变得非常容易,因为这是一个如此普遍的问题。再说一遍,他们在开车时睡着了,而且他们的文档也很糟糕。

The quickest solution: just use the stringy method...

.replacingOccurrences(of: " ", with: "%20")

...at the end of your string, and it will do as it says.

Apple should be EMBARRASSED that their URL(string: ) method doesn't automatically do this (and more). It's 2023 and I wasted 3 hours finding this half-assed solution.

My specific example was inside cellForItemAt and having to do with optionals.

let stringOfImageURLFromFirebase = wordController?.word?.images[indexPath.item].imgUrl

let stringWithNoSpaces = string?.replacingOccurrences(of: " ", with: "%20")

if let imageURLString = stringWithNoSpaces,
   let imageURL = URL(string: imageURLString) {
         cell.definitionImageView.loadImageFromFirebase(url: imageURL)
    } else {
        cell.definitionImageView.image = UIImage(named: "slictionarylogo")
    }

You can fuddle with .addingPercentEncoding for a long time, try NSURL nonsense, and you'll just be faster with using the obvious. Apple sucks, and should've made this painfully easy since it's such a common problem. Again, they are asleep at the wheel, and their documentation is AWFUL too.

云醉月微眠 2024-09-20 16:27:50
var urlString :String = originalUrl.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!
var urlString :String = originalUrl.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!
音盲 2024-09-20 16:27:50

希望这会起作用

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)    
}

它会从网址中删除所有类型的空格。

Hope this will work

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)    
}

It will remove all kind of spaces from the url.

花海 2024-09-20 16:27:50

Swift 5.3,清除字符串空间,

let str = "  www.test.com  "
let trimmed = str.trimmingCharacters(in: .whitespacesAndNewlines)
print(str) // "www.test.com" 

Swift 5.3, clear space your string,

let str = "  www.test.com  "
let trimmed = str.trimmingCharacters(in: .whitespacesAndNewlines)
print(str) // "www.test.com" 
浊酒尽余欢 2024-09-20 16:27:50

SWIFT 3.1

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

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

SWIFT 3.1

Simple way to replace an empty space with replacingOccurrences:

URL = URL.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
骷髅 2024-09-20 16:27:50

斯威夫特 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, 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)!
孤者何惧 2024-09-20 16:27:50

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

URL(fileURLWithPath: String) 

A Swift 4 solution. You simply pass through a string and it fills spaces with %20 and adds "http://" to the beginning to the string. Pretty sweet!

URL(fileURLWithPath: String) 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文