如何将特殊字符串转换为url?

时间:2016-12-19 08:34:19

标签: ios iphone string swift3 url-encoding

我有一个url字符串,显示带路径的静态地图

let stringUrl = "https://maps.googleapis.com/maps/api/staticmap?size=1000x500&maptype=roadmap&markers=icon:http://api.appcargo.com/app_images/ic_pin.png%7C23.0225,72.5714&markers=icon:http://api.appcargo.com/app_images/ic_pin_destination_toolbar.png%7C22.8297927,72.3637811&path=color:0xff0000ff%7Cweight:5%7Cenc:sqokCmb}yLjA?\\Bb@H`@Lb@T|A|AZd@dFrDvD|CbF`Ef@TnCvBlG|EbF|D~DfC|BvAdB`AjB|@pAd@xGjCd@Lh@TXXZf@tBhEz@fB^v@V|@t@zDl@~Bt@|AbAnAj@n@fAfA`@h@NZr@rBf@hBrApD\\r@f@tA`@p@ZZH?HBNLHR?PEPl@fAj@t@rAvAt@n@jAhARVV`@Tl@V`A^`D\\zCZ|CDb@HZRb@VVr@h@l@Z`A\\d@X^^~@nAr@fAhCpFt@nBpAxDnBzFz@nCjBrGv@xCl@xDHn@Np@pAfJtAnJJdAXrBt@jFdBnLvBzMfCjNhCbO\\dBv@|CpIbYfB~Fb@xA`AfDVpAj@hDl@|EbAnHb@dD\\dD`AlO^rIXvFZvAXz@l@pAB?FBDN@BjB`D`AxAhCrDnFdHtUvYrCnD^j@NTHFBHNJTNnDjEzCzCrEjEvObO~SbSpJ`JtCtCfMzLvInIfCzBzDvC\\Vj@VZFJ?NBRNLV@P?FADVRfF`EvGpFtO~LzClCjWtSrZlVtKtInCtBvE|DxXlUx\\fXvFxEjFfEdBpA|E|DdA|@`MjKhAx@z@~@vCjChIlHlQbPzOxNhTrRlDfDzDhDvAvA`JdIlGzFvTdS`DnCxAzAjGdGxR~PjFhFrEbEtJvI|PjOtNjMxJbJ~K|JrGbGrCbClKpJji@jf@|e@bc@zo@ll@pBdBlA|@rE~ClXfRrZxSjx@dj@pGnEfA|@`B`Bx@dAtClEvAlCzApCTPVJf@FdAM|E[|JiAxG{@jG{@`AM\\Rb@N~@T\\LJHPl@\\dAH@NB@jBFvDdDGUxAW|C%60@sA&format=jpg"

let mapUrl = URL(string: stringUrl)

它给了我nil的价值。任何完美编码的方法都可以在浏览器中加载而不会出错

1 个答案:

答案 0 :(得分:0)

if let encodedString = stringUrl.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
    let mapUrl = URL(string: encodedString)
}