An object-c alternative to encodeURIComponent

Having difficulty finding information on this through a search engine.

Is there a similar method in Objective-C for encoding URI components?

http://www.w3schools.com/jsref/jsref_encodeuricomponent.asp

This is a common task, but I am unable to locate any documentation specific to Objective-C.

Appreciate any insights.

Answer №2

Sure, feel free to utilize these methods. I believe they will be beneficial.

//encode URL string

+(NSString *)URLEncodedString:(NSString *)str
{

    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)str,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));

    return encodedString;
}

}

//decode URL string

+(NSString *)URLDecodedString:(NSString *)str
{

  NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)str, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));

    return decodedString;
}

Answer №3

There has been a deprecation of the method

stringByAddingPercentEscapesUsingEncoding:
. The equivalent method for iOS 7 and above is encodeURIComponent:

[str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]

Answer №4

Avoid using the deprecated methods

CFURLCreateStringByAddingPercentEscapes
and
stringByAddingPercentEscapesUsingEncoding
.

Although Dave's answer is on the right track, it lacks specificity.

Instead of using

NSCharacterSet.URLQueryAllowedCharacterSet
, manually create a character set based on the documentation for encodeURIComponent():

A–Z a–z 0–9 - _ . ! ~ * ' ( )

Here is an improved solution:

+ (NSString *)encodeURIComponent:(NSString *)uriComponent {
    NSString *allowedChars = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                              "abcdefghijklmnopqrstuvwxyz"
                              "0123456789"
                              "-_.!~*'()";

    NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:allowedChars];
    return [uriComponent stringByAddingPercentEncodingWithAllowedCharacters:charSet];
}

+ (NSString *)decodeURIComponent:(NSString *)uriComponent {
    return [uriComponent stringByRemovingPercentEncoding];
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best approach to integrating an idle timeout feature with identityserver4 and aspnet identity for a secure implementation?

Currently, I am developing a login site using IdentityServer4 (server UI) with .NET Identity in .NET Core 2.2 Razor Pages. I have implemented a javascript modal alert that notifies users of an impending idle timeout and redirects them to the logout screen ...

Tips for showing validation message just one time along with multiple error messages

Exploring ways to implement a dynamic form submit function using jQuery. $('#btnsumbit').click(function() { $('.required_field').each(function() { if ($(this).val() == "") { alert('please fill field'); ret ...

Looking for a fully customizable event and booking calendar?

Currently, I am searching for a unique event and booking calendar that provides the ability to customize each cell or day with our desired content. While most calendars only allow for inputting events as text, we require a solution that enables us to add ...

What potential issues arise from utilizing useRef alongside useSelector?

Although I have the capability to access the store by using thunks and/or global stores, I avoid binding my component to the Redux store. This is because the component will be utilized with various stores both inside and outside of the project. The compone ...

Using Firebase with Arrays in Javascript

Currently, my team and I are working on a project using Firebase with Vue.js as the framework. We've come across a challenge regarding creating, updating, and deleting elements in a Firebase cloud document. For instance, within our 'people&apos ...

I'm curious about the correct method for updating a parent component using a shared service within the ngOnInit function in Angular version 13

There have been instances where I encountered a scenario multiple times, where I utilize a shared service within the ngOnInit of a component to update a value in another component, specifically its parent. This often leads to the well-known Error: NG0100: ...

What methods can I use to integrate a Google HeatMap into the GoogleMap object in the Angular AGM library?

I am trying to fetch the googleMap object in agm and utilize it to create a HeatMapLayer in my project. However, the following code is not functioning as expected: declare var google: any; @Directive({ selector: 'my-comp', }) export class MyC ...

Creating a sliding bottom border effect with CSS when clicked

Is there a way to animate the sliding of the bottom border of a menu item when clicked on? Check out the code below: HTML - <div class="menu"> <div class="menu-item active">menu 1</div> <div class="menu-item">menu 2</ ...

Is it possible to deactivate the onclick event following a successful ajax request?

I am looking to disable the onclick event after a successful ajax request. <div class="report_button" id="report_button" title="Reportthis" style="width:65px;height:15px;" onclick="reported_text(user_id,lead_id);">Report</div> This is the div ...

Using React.JS: Display Object Map in rendering

I have an object with family information that looks like this: Family: Parent0: BirthPlace: "dsa" Birthday: "2021-01-04" Relationship: "dsa" SurnameAndName: "dasdsa" Parent1: BirthPlace: & ...

Increase the size of the grid system column upon clicking on a Bootstrap icon

I am using Google Maps in a tab with Bootstrap, but the map is too small. I would like to change the Bootstrap grid system when I click on a FontAwesome icon: the first column should turn into col-md-8, and the second column should become col-md-4. Here i ...

Tips on how to eliminate items from a list that do not include a specific character

I need help with a list that has a specific format /listing/vasita-otomobil-volkswagen-boyasiz-2016-passat-variant-1.6-tdi-dsg-higline-sunroof-hayalet-819608311/detail,#,#,,/listing/vasita-otomobil-volkswagen-boyasiz-2016-passat-variant-1.6-tdi-dsg-higline ...

Determining the quantity of items within a div using jQuery

Similar Question: Retrieve the count of elements inside parent div using jQuery Can you determine the total number of elements within a specific div? <div id=count"> <span></span> <span></span> <span></ ...

I could use some assistance with deciphering JSON data

After using console.log to display the data I received, I observed an object structured as follows (I trimmed some details for clarity and used ... to indicate repetitive information): [ Submission { title: 'Untitled', content: { ur ...

"In strict mode, the object is subjected to specific rules

I am facing a challenge with an object in my project that needs to run the content of the page within strict mode. Even after attempting to return it for global scope usage, I still haven't been able to resolve the issue. (function($) { "use stric ...

Is there a way to set a custom width or make the description responsive?

Is there a way to ensure that the description is responsive and automatically goes to the next line instead of extending horizontally? Although using textField could fix this issue, I also need to adjust the padding and outline. Are there any alternative s ...

"Vue is throwing an error because it cannot set the property '$offlineStorage' on an undefined object. How can this issue be resolved

While working on my vue ionic app, I integrated the plugin available at https://github.com/filrak/vue-offline. However, upon installing the plugin, an error was encountered: vue-offline.js?bf4e:193 Uncaught TypeError: Cannot set property '$offlineStor ...

Unable to apply ready function in jquery .load

When the document is ready, the following code is executed: jQuery(document).ready(function(){ jQuery('#button').click(function() { jQuery('#contact_form').load("/Users/mge/Downloads/jquery-ajax-1/readme.txt"); ...

Utilizing an external type definition in JSDoc @typedef

I'm encountering an issue with reducing redundancy when defining my imported types. I am trying to streamline the process, but unfortunately I am running into errors. /** @typedef {import("../types/util")} util @typedef {util.mapBehaviors} m ...

Having trouble retrieving coordinates from AJAX request to Google Maps API?

I am currently developing a weather application and one of the initial steps is to retrieve the longitude and latitude coordinates for a specific city based on its name. To achieve this, I am utilizing Google Maps API to gather the necessary information. ...