I am getting something when I convert string to NSURL.
My code id...
NSString *urlString = [[NSString alloc]initWithFormat:#"http://host name/index.php?id=%#&mob=%#&name=%#&mail=%#&m=23", self.deviceId, self.pnumber, self.name, self.email];
urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *urlPattern = [NSURL URLWithString:urlString];
NSLog(#"%#", urlPattern);
http://host name/index.php?dev_id=73EA1D1D-E6E3-485C-883D-DF952E116&mob=%3CUITextField:%200x7fe247063c00;%20frame%20=%20(0%20128.333;%20310.667%2040.6667);%20text%20=%20'';%20opaque%20=%20NO;%20autoresize%20=%20RM+BM;%20gestureRecognizers%20=%20%3CNSArray:%200x608000244c50%3E;%20layer%20=%20%3CCALayer:%200x60800003eee0%3E%3E&name=%3CUITextField:%200x7fe247055800;%20frame%20=%20(0%2044;%20310.667%2040.3333);%20text%20=%20'';%20opaque%20=%20NO;%20autoresize%20=%20RM+BM;%20gestureRecognizers%20=%20%3CNSArray:%200x608000244410%3E;%20layer%20=%20%3CCALayer:%200x60800003e240%3E%3E&mail=%3CUITextField:%200x7fe24601ae00;%20frame%20=%20(0%20213;%20310.667%2040.3333);%20text%20=%20'';%20opaque%20=%20NO;%20autoresize%20=%20RM+BM;%20gestureRecognizers%20=%20%3CNSArray:%200x608000243c90%3E;%20layer%20=%20%3CCALayer:%200x60c000038580%3E%3E&m=23
How to convert string to NSURL
Probably you are assigning textfield to urlString. Check for self.pnumber whether its a textfield or string. If textField then set as self.pnumber.text and similarly check for all data.
change self.pnumber, self.name, self.email to self.pnumber.text, self.name.text, self.email.text
use like
NSString *urlString = [[NSString alloc]initWithFormat:#"http://host name/index.php?id=%#&mob=%#&name=%#&mail=%#&m=23", self.deviceId, self.pnumber.text, self.name.text, self.email.text];
Try This
let NSHipster = URL(string: "http://nshipster.com/") //returns a valid URL
let invalidURL = URL(string: "www.example.com/This is a sentence") //Returns nil
for more detail:
http://www.codingexplorer.com/creating-and-modifying-nsurl-in-swift/
Related
I need to send french string "Commentaire d’arret" to webservice in objective c.
But my app crashes when I am sending this string as parameter to service. And normal string like "india" is working fine.
Can any one help me.
Encode your parameter for a GET request:
let param = "Commentaire d’arret"
let encodedParam = (param as NSString).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
Results in Commentaire%20d%E2%80%99arret.
If you want to send a POST request prepare your post body like this:
let postString = "param=consultés"
let postData = postString.data(using: .utf8)
Objective-C
NSString *param = #"Commentaire d’arret";
NSString *encodedParam = [param stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSString *postString = #"param=consultés";
NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
As you said I have checked your code and you need to do encoding before converting to your URL. try this.
NSString *searchApi = [NSString stringWithFormat:#"xxx/xxx/index?
q=#consultés"];
searchApi = [searchApi stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *tempURL = [NSURL URLWithString:searchApi];
Try this:
NSString *strParam = #"Commentaire d’arret";
NSString *encodedParam = [strParam stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
Below is the string that I need to create as a url for GET request. I am always getting nil in NSURL.
Can anyone help me ?
http://example.com/webexternal1/api/Values/sendorder?orderlist={code:"122|155",rate:"60|5",qty:"5|5"}&tab=N2
//strParams = {code:122|155,rate:60|5,qty:5|5}&tab=N2
dataUrl = [#"http://example.com/webexternal1/api/Values/sendorder?orderlist=" stringByAppendingString:strParams];
urlComponants = [[NSURLComponents alloc]initWithString:dataUrl];
NSURL *url = urlComponants.URL;
Try url encoding the strParams.
NSString* strParams = [#"{code:122|155,rate:60|5,qty:5|5}&tab=N2" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
I have a UISearchBar from which I'm extracting the text that represents an address and building from it a JSON URL for Google Geocoder.
NSString* address = searchbar.text;
NSString* url = [NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?address=%#&sensor=false", address];
If I copy & paste the url from debug window to the browser it works like a charm but when I try to convert it to NSURL i get nil
NSURL* theUrl = [NSURL URLWithString:url];
Any ideas?
I added the encoding to the address prior to concatenating the url and that fixed the problem so now the code looks like this:
NSString* address = searchbar.text;
NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, CFBridgingRetain(address), NULL, (CFStringRef)#"!*'();:#&=+$,/?%#[]", kCFStringEncodingUTF8));
NSString* url = [NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?address=%#&sensor=false", encodedString];
I used this code from the Stack Overflow question: URLWithString: returns nil:
//localisationName is a arbitrary string here
NSString* webName = [localisationName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* stringURL = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#,Montréal,Communauté-Urbaine-de-Montréal,Québec,Canadae&output=csv&oe=utf8&sensor=false", webName];
NSString* webStringURL = [stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:webStringURL];
When I copied it into my code, there wasn't any issue but when I modified it to use my url, I got this issue:
Data argument not used by format string.
But it works fine. In my project:
.h:
NSString *localisationName;
.m:
NSString* webName = [localisationName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* stringURL = [NSString stringWithFormat:#"http://en.wikipedia.org/wiki/Hősök_tere", webName];
NSString* webStringURL = [stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:webStringURL];
[_webView loadRequest:[NSURLRequest requestWithURL:url]];
How can I solve this? Anything missing from my code?
The # in the original string is used as a placeholder where the value of webName is inserted. In your code, you have no such placeholder, so you are telling it to put webName into your string, but you aren't saying where.
If you don't want to insert webName into the string, then half your code is redundant. All you need is:
NSString* stringURL = #"http://en.wikipedia.org/wiki/Hősök_tere";
NSString* webStringURL = [stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:webStringURL];
[_webView loadRequest:[NSURLRequest requestWithURL:url]];
The +stringWithFormat: method will return a string created by using a given format string as a template into which the remaining argument values are substituted. And in the first code block, %# will be replaced by value of webName.
In your modified version, the format parameter, which is #"http://en.wikipedia.org/wiki/Hősök_tere", does not contain any format specifiers, so
NSString* stringURL = [NSString stringWithFormat:#"http://en.wikipedia.org/wiki/Hősök_tere", webName];
just runs like this (with the warning Data argument not used by format string.):
NSString* stringURL = #"http://en.wikipedia.org/wiki/Hősök_tere";
How do I convert an NSString value to NSData?
NSString* str = #"teststring";
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSString *str = #"helowrld";
// This converts the string to an NSData object
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
you can take reference from this link
Do:
NSData *data = [yourString dataUsingEncoding:NSUTF8StringEncoding];
then feel free to proceed with NSJSONSerialization:JSONObjectWithData.
Correction to the answer regarding the NULL terminator
Following the comments, official documentation, and verifications, this answer was updated regarding the removal of an alleged NULL terminator:
As documented by dataUsingEncoding::
Return Value
The result of invoking dataUsingEncoding:allowLossyConversion: with NO as the second argument
As documented by getCString:maxLength:encoding: and cStringUsingEncoding::
note that the data returned by dataUsingEncoding:allowLossyConversion: is not a strict C-string since it does not have a NULL terminator
In case of Swift Developer coming here,
to convert from NSString / String to NSData
var _nsdata = _nsstring.dataUsingEncoding(NSUTF8StringEncoding)
Objective-C:
NSString *str = #"test string";
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:str];
NSString *thatStr = [NSKeyedUnarchiver unarchiveObjectWithData:data];
Swift:
let str = "test string"
let data = NSKeyedArchiver.archivedData(withRootObject: str)
let thatStr = NSKeyedUnarchiver.unarchiveObject(with: data) as! String
First off, you should use dataUsingEncoding: instead of going through UTF8String. You only use UTF8String when you need a C string in that encoding.
Then, for UTF-16, just pass NSUnicodeStringEncoding instead of NSUTF8StringEncoding in your dataUsingEncoding: message.
For Swift 3, you will mostly be converting from String to Data.
let myString = "test"
let myData = myString.data(using: .utf8)
print(myData) // Optional(Data)
NSString *str = #"hello";
NSData *data = [NSData dataWithBytes:str.UTF8String length:str.length];
Objective-C:
NSString to NSData:
NSString* str= #"string";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];
NSData to NSString:
NSString* newStr = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];
Swift:
String to Data:
var testString = "string"
var somedata = testString.data(using: String.Encoding.utf8)
Data to String:
var backToString = String(data: somedata!, encoding: String.Encoding.utf8) as String!
Update Swift 5.x
let str = "teststring"
let data = str.data(using: .utf8)
Swift:
Swift 5.x
let myStringToConvert = "My String to Convert in Data"
let myData = myStringToConvert.data(using: .utf8)
String to Data:
var myStringToConvert = "My String to Convert in Data"
var myData = myStringToConvert.data(using: String.Encoding.utf8)
Data to String:
var backToMyString = String(data: myData!, encoding: String.Encoding.utf8) as String!
OBJECTIVE C:
NSString to NSData :
NSString* myStringToConvert= #"My String to Convert in Data";
NSData* myData=[str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSData to NSString :
NSString* backToMyString = [[NSString alloc] initWithData: myData encoding:NSUTF8StringEncoding];
NSString *str = #"Banana";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:true];
Objective-C
NSString *str = #"Hello World";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
Swift
let str = "Hello World"
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: false)
In Swift there is an API which returns a non-optional
let str = "teststring"
let data = Data(str.utf8)