-2

I have PAI its Implemented in .NET.

one of the web service url is like this

http://123.321.33/UploadCitizenImage?jsonString={\"Mobile\":\"12345678\", \"fileName\":\"7661832460_05072018.png\"} 

while converting above string to URL in swift, app going crash.

for more info check this
Error Screenshot

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 1
    You have a space after a ",", it's not valid. You need to percent escape some characters. – Larme May 07 '18 at 07:26
  • This is _not_ a duplicate of [How to convert this var string to NSURL in swift](https://stackoverflow.com/questions/24410473/how-to-convert-this-var-string-to-nsurl-in-swift) as this question is about _why does it crash?_ – DarkDust May 07 '18 at 08:16

3 Answers3

2

The URL(string:) initializer returns an optional since the parsing of the string may fail. In that case, nil is returned. That's exactly what's happening here since the string you are providing is not a valid URL: there are several characters in the query that are not allowed there and need to be replaced: { as %7B, " as %22, space as %20 and } as %7D.

So the initializer returns nil. Next thing you do is force unwrap via the ! operator. But force-unwrapping a nil is illegal and is why you get the crash.

If you want to create an URL, please look into the URLComponents class which does all the necessary escaping for you so you don't need to care about it. The queryItems property is of particular interest for you, it's an array of URLQueryItem.

DarkDust
  • 90,870
  • 19
  • 190
  • 224
1

Please do something like that,

let jsonString = "jsonString={\"Mobile\":\"12345678\", \"fileName\":\"7661832460_05072018.png\"}" as String
let urlEncoadedJson = jsonString.addingPercentEncoding(withAllowedCharacters:.urlHostAllowed)
let urls = NSURL(string:"http://123.321.33/UploadCitizenImage?\(urlEncoadedJson ?? "")")

First convert your json into encodedJson then add into your url. Do let me know if there is some issue.

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
aBilal17
  • 2,974
  • 2
  • 17
  • 23
0

You can try this,

let string = "http://123.321.33/UploadCitizenImage?jsonString={\"Mobile\":\"12345678\", \"fileName\":\"7661832460_05072018.png\"}"
let escapedString = string.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let url = URL(string: escapedString!)!
print(url)

Output will be like this,

http://123.321.33/UploadCitizenImage?jsonString=%7B%22Mobile%22:%2212345678%22,%20%22fileName%22:%227661832460_05072018.png%22%7D
PPL
  • 6,357
  • 1
  • 11
  • 30