Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
963 views
in Technique[技术] by (71.8m points)

string - How to prepend url with http:// using stringWithFormat in Swift

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...