String.removingPercentEncoding возвращает ноль для особенно больших строк - PullRequest
1 голос
/ 18 мая 2019

Я создаю приложение, которое показывает события, которые находятся рядом с пользователем.Некоторые из этих событий удалены из Интернета, а некоторые опубликованы в моем бэкэнде от пользователей приложения.Те, которые были опубликованы в серверной части, возвращаются со строковым свойством description, которое закодировано в процентах от URL (это связано с хранением эмодзи в моей базе данных SQL, и это совсем другая история).

Когда события извлекаются из моего API, некоторые события будут иметь процентное кодирование, в то время как другие не будут .Обычно при использовании String.removingPercentEncoding в строке, которая не закодирована, ничего в строке не меняется.

Пример:

let example = "This is an example text"
let decodedExample = example.removingPercentEncoding!
print(decodedExample)

Приведенный выше код возвращает This is an example text.

Теперь, с особенно длинными строками описания событий, которые не имеют процентное кодирование, мы используем тот же метод и ожидаем, что он просто вернет ту же строку.Однако я обнаружил, что вызов .removingPercentEncoding для одной из этих очень длинных строк на самом деле возвращает nil.Строка в следующем примере содержит 3123 символов.

Пример:

print("Encoded event description: ", event.description!)
print("Decoded event description: ", self.event.description.removingPercentEncoding ?? "Decoding failed")

Вышеприведенный код возвращает:

Encoded event description:  The Experience:\nThe Pavel Barber Hockey School is coming to St. Louis May 17th - 19th, 2019! Join head instructor Pavel Barber, a world renown stickhandling and shootout specialist, and friends for an experience that will challenge these young athletes to get better and encourage mental and physical skill development in a fun and creative environment. \nThe Features:\n\n\n4 Hours On-Ice Skill Development: 1 Hour Friday, 2 Hours Saturday, 1 Hour Sunday\n\n\n4 Hours Off-Ice Skill Development w/ Our Floorball+ HKY Training Program: 1 Hour Friday, 2 Hours Saturday, 1 Hour Sunday\n\n\n1 Personal Growth Group Session Saturday and Sunday\n\n\nScrimmage Game on Sunday\n\n\nPavel Barber Jersey and Socks Included\n\n\nLunch Included Saturday and Sunday\n\n\n \nThe Schedule:Friday, May 17th, 2019 - Day 1 - 5:30 pm - 8 pmSaturday, May 18th, 2019 - Day 2 - 7:30 am - 2 pmSunday, May 19th, 2019 - Day 3 - 7:30 am - 12:30 pm*Times and location subject to change. \n \nOther School Info:\n\n\nSpace is limited and will be filled on a first come, first serve basis\n\n\nAge groups include 7-10 year olds, 11-12 year olds, 13-15 year olds\n\n\nSkill Level Requirements - Kids should be proficient in the basics of hockey before attending the school\n\n\nRefund Policy: Refunds will only be allowed 30 days prior to the start of the school. All refunds are subject to a 20% cancellation fee.\n\n\nThis is not an overnight camp. All kids will need to be picked up and dropped off daily.\n\n\nPlease send your child with the following items each day of the school: workout clothes (such as shorts, t-shirt and gym shoes) for the off-ice sessions and sunscreen as there will be some outdoor activity. Water will be available for the players for all on-ice and off-ice training sessions.\n\n\nPavel Barber and Floorball Merch will be available at the school as well, but we recommend adding to your order now to ensure sizing and product availability\n\n\n \nAbout Pavel Barber:Pavel Barber has quickly emerged as one of the most sought after stick handling and skill development insturctors in the world. He is an internet hockey legend for his incredible hands, creative shootout moves and dangles and his skill development work. His YouTube channel has over 23 MILLION views on it and growing. Barber specializes in stick handling, shoout moves and creative skill development for both hockey and floorball. In fact, he is obsessed with it. He has studied talent generation across all fields and enjoys passing on that knowledge and training hockey players of all ages and skill levels.\nIn 2016, Barber was selected to the Team Canada National Floorball team that competed in Riga at the World Floorball Championships. \nBarber is a GoPro sponsored athlete and has played Indoor Hockey and Field Hockey for Team Canada between 2010 and 2015.\nOriginally from Toronto, Barber currently resides in Vancouver (or anywhere he can have a stick and puck/ball in his hands).\n\nPrice: $350 – $450\n\nFor more info, click here: https://www.eventbrite.com/e/pavel-barber-hockey-school-st-louis-registration-46948450078?aff=ebdssbdestsearch

Decoded event description:  Decoding failed

Любая идея, почему String.removingPercentEncoding работает обычнодлинные строки, но возвращает nil для очень больших строк (3000+ символов)?

1 Ответ

1 голос
/ 18 мая 2019

Я пробовал несколько миллионов раз со случайной строкой длиной более 3000, и не могу воспроизвести ту же проблему.

Ваш event.description! имеет символ процента без экранирования, что является причиной removingPercentEncoding fails.

...to a 20% cancellation...

Длина строки не имеет значения.

Как правило, removingPercentEncoding завершается неудачно, если исходная строка содержит неэкранированные символы процента.

Youлегко проверить:

let str = "20%"

print(str.removingPercentEncoding ?? "*fail*") //->*fail*

Если исходная строка может содержать символы процента, всегда применение removingPercentEncoding не будет хорошей стратегией.

...