23

I'm building a custom browser using UIWebView.

Use case: User enters "www.abc.com" into the address bar. Error below thrown:

Error Domain=WebKitErrorDomain Code=102 "Frame load interrupted" UserInfo=0x19860770 {NSErrorFailingURLKey=file://www.abc.com, NSErrorFailingURLStringKey=file://www.abc.com, NSLocalizedDescription=Frame load interrupted}

Reason: the URL needs to be prepended with "http://"

I would like to use the stringWithFormat method of NSString, but I can't seem to get the syntax correct. In Objective-C, we have;

NSString* modifiedURLString = [NSString stringWithFormat:@"http://%@", urlString];

In Swift, the method is not there?!

var modifiedURLString: String = String(`stringWithFormat not here?!...`)

I then tried mixing Objective C with Swift:

var modifiedURLString: NSString = [NSString stringWithFormat not here?!...

Then I tried straight-up Objective-C:

NSString* modifiedURLString = [NSString stringWithFormat:@"http://", urlString];

Thank you for your help. Sincerely, Keith

rmaddy
  • 314,917
  • 42
  • 532
  • 579
kmiklas
  • 13,085
  • 22
  • 67
  • 103
  • 3
    The intended `"http://" + suffix` didn't just work? – Tommy Jun 16 '14 at 15:34
  • I was using this tutorial. Look under "Correcting User Input" http://iosdeveloperzone.com/2011/05/22/tutorial-building-a-web-browser-with-uiwebview-part-3/ – kmiklas Jun 16 '14 at 15:39

3 Answers3

65

The equivalent of NSString's formatWithString: is just "format:", as shown below, but there is no real need to do that for the example you have given. Just append strings, or use interpolation...

let urlString = "www.abc.com"
var modifiedURLString = NSString(format:"http://%@", urlString) as String
// or just
modifiedURLString = String(format:"http://%@", urlString)
// or
let simpler = "http://" + urlString
// or use string interplotaion
let simplest = "http://\(urlString)"
Grimxn
  • 22,115
  • 10
  • 72
  • 85
17

Just for the sake of being complete here (though of a 4th way), here are your options:

1: Swift way of using NSString's stringWithFormat:

let url = NSString(format: "http://%@", aSuffix)

2: Take advantage of Swift's ability concatenate strings with the "+" operator.

let url = "http://" + aSuffix

3: Use NSString's stringByAppendingString() method.

let url = "http://"
url.stringByAppendingString(aSuffix)

4: String interpolation.

let url = "http://\(aSuffix)"
Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
8

You can use string interpolation:

let site = "www.abc.com"
let url = "http://\(site)"
Ferruccio
  • 98,941
  • 38
  • 226
  • 299
  • Just wondering about this, what os the format comes from the NSLocalizedString? Is there a Swift method to do this? – rckoenes Jun 19 '14 at 14:58