0

I'm dealing with an issue here, I have a URL of an image which is like this

http://example.com/image/test.jpg

Which is a string.

And I would like to insert before .jpg a certain text like -40x40

Is there any way to analyze the URL string and somehow to add this text so the final string should be

http://example.com/image/text-40x40.jpg

What i've tried till now is this

var finalImage = "http://example.com/image/test.jpg"
finalImage.insert("-40x40" as Character, at: finalImage.endIndex - 4)

but i get 2 errors.

1) i cant add more than 1 character and 2) i cant do the math ad endIndex.

But i can't add more than one character there.

Thanks a lot!

6 Answers 6

4

Try this. It uses NSURL, which exists so that path manipulations are easy and legal! The documentation is really quite good.

let s1 = "http://example.com/image/test.jpg"
let u = URL(fileURLWithPath: s1)
let exExt = u.deletingPathExtension()
let s2 = exExt.absoluteString + "-40x40.jpg"
Sign up to request clarification or add additional context in comments.

Comments

3

Another ways.

The code shown in the question, fixed:

var finalImage = "http://example.com/image/test.jpg"
let extIndex = finalImage.index(finalImage.endIndex, offsetBy: -4)
finalImage.insert(contentsOf: "-40x40".characters, at: extIndex)

Using NSRegularExpression:

let origImage = "http://example.com/image/test.jpg"
let regex = try! NSRegularExpression(pattern: "(\\.jpg)$", options: .caseInsensitive)
let finalImage = regex.stringByReplacingMatches(in: origImage, range: NSRange(0..<origImage.utf16.count), withTemplate: "-40x40$0")

Comments

2

As a complement to the neat accepted answer by @Grimxn: Foundation's URL has various more methods that allows for more separation "of concerns" in case you'd like to apply some more complex modification of the image (file) name, while not really worrying about the image (file) name extension.

let s1 = "http://example.com/something.cgi/image/test.jpg"
let u = URL(fileURLWithPath: s1)

// separate into (String) components of interest
let prefixUrl = u.deletingLastPathComponent().absoluteString 
    // "http://example.com/something.cgi/image/"
let fileName = u.deletingPathExtension().lastPathComponent   
    // "test"
let fileExtension = "." + u.pathExtension                    
    // ".jpg"

// ... some methods that implements your possibly more 
// complex filename modification
func modify(fileName fName: String) -> String {
    // ...
    return fName + "-40x40"
}

// reconstruct url with modified filename
let s2 = prefixUrl + modify(fileName: fileName) + fileExtension
print(s2) // http:/example.com/something.cgi/image/test-40x40.jpg

1 Comment

I almost put this into my answer, but favoured brevity. Thanks for "completing" my answer!
2

Grimxn's solution is probably the best fit for this problem, but for more complex manipulation of URLs, take a look at the NSURLComponents class. You can convert an NSURL to NSURLComponents, then use the various methods of NSURLComponents to manipulate your URL, and then finally convert the NSURLComponents back to an NSURL

As noted in a comment by @dfri, Swift 3 (and later) includes a native URLComponents class, which follows Swift naming and calling conventions. Going forward you should use that instead of the Objective-C/Swift 2 NSURLComponents class.

2 Comments

+1 for this, just a prompt: in Swift 3, we needn't really mention NSUrlComponents, as we will only work with the native URLComponents (a structure bridging to the former Obj-C class).
I figured as much, but I've been developing for a client using Swift 2, and haven't made the switch to Swift 3 yet, so I didn't want to misstate.
1
if let url = NSURL(string: "http://example.com/image/test.jpg"),withoutExt = url.URLByDeletingPathExtension
{
       let finalstring : NSString = withoutExt.absoluteString + "-40x40.jpg"
       print(finalstring)
}

1 Comment

@KwnstantinosNatsios R u Using swift 3.0 ?
1

Very simply with one line...

let newURL = oldURL.stringByReplacingOccurrencesOfString(".jpg", withString: "-40x40.jpg", options: NSStringCompareOptions.LiteralSearch, range: nil)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.