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]];
Related
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/
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'm keep getting a (null) error when I try to build my NSURL to open another app.
The URL should be
ms-test-app://eventSourceId=evtSrcId&eventID=13675016&eventType=0&json={"meterresults":[{"clean":"2","raw":"2","status":"0"}]}
but when I try to build my URL it's always null.
At first I thought it has something to do with the URL itself, but it's the same as I got it from the example here.
Another thought was that IOS got some problems with the double quotes in the JSON, but I replaced them with %22, but this doesn't work either.
Here is the code, where I build the URL:
NSString *jsonString = [NSString stringWithFormat:#"{%22meterresults%22:[{%22clean%22:%22%#%22,%22raw%22:%22%#%22,%22status%22:%22%#%22}]}", cleanReadingString, rawReadingString, status];
NSLog(#"JSON= %#",jsonString);
//Send the result JSON back to the movilizer app
NSString *eventSourceId = #"evtSrcId";
NSString *encodedQueryString = [NSString stringWithFormat:#"?eventSourceId=%#&eventID=%d&eventType=0&json=%#",
eventSourceId, _eventId, jsonString];[NSCharacterSet URLQueryAllowedCharacterSet]]
NSString *urlStr = [NSString stringWithFormat:#"%#%#",
[_endpointUrls objectForKey:[NSNumber numberWithInt:(int)_selectedEndpoint]],
encodedQueryString];
NSURL *url = [NSURL URLWithString:urlStr];
I don't know where I'm wrong and I would be glad if someone got any idea.
Thanks in advance.
You should really be using NSURLComponents to create URLs rather than trying to format them into a string.
NSDictionary* jsonDict = #{#"clean": #"2", #"raw": #"2", #"status": #"0"};
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:NULL];
NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSURLComponents* components = [[NSURLComponents alloc] init];
components.scheme = #"ms-test-app";
components.queryItems = #[
[[NSURLQueryItem alloc] initWithName:#"eventSourceId" value:eventSourceId],
[[NSURLQueryItem alloc] initWithName:#"eventID" value:#(_eventId).stringValue],
[[NSURLQueryItem alloc] initWithName:#"json" value:jsonString]
];
NSURL* url = components.URL;
Once you build the URL that way, it becomes apparent that your string doesn't have a host portion (or more accurately, one of your parameters is being used as the host portion).
The other comments about not being able to send JSON as an URL parameter are incorrect. As long as the system on the other side that is parsing the query string can handle it, you can send anything you want as an URL parameter.
I'm trying to get data from an API in swift using alamofire.
The link is like this:
www.something.com?date1=2015-06-04&date2=2015-06-04&id=1
How do I pass the parameters?
Make a dictionary of parameters ....and just passed it like
let param = [ "date1" : "2015-06-04",
"date2" : "2015-06-04",
"id" : 1
]
//and passed it in request
Alamofire.request(.GET, "www.something.com", parameters:param)
You can use the following code
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["date1": "2015-06-04", "date2":"2015-06-04", "id":1])
.response { (request, response, data, error) in
println(request)
println(response)
println(error)
}
Add parameters into the NSMutableDictionary and than append dictionary with URL string. It's easy for me.
I have example in Objective C. May be it's Usefull to you.
NSMutableDictionary * dictParam = [[NSMutableDictionary alloc]init];
[dictParam setObject:txtMessage.text forKey:#"Desctiprion"];
[dictParam setObject:type forKey:#"Type"];
NSString *strUrl = [NSString stringWithFormat:#"http://example.com"];
NSString *strParameter = #"";
NSString *strData;
if (dictParam != nil) {
strParameter = [self encodeDictionaryToString:dictParam];
strData = [NSString stringWithFormat:#"%#?%#",strUrl,strParameter];
}else{
strData = [NSString stringWithFormat:#"%#",strUrl];
}
NSString *strURL = [strData stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:strURL];
NSLog(#"%#",url);
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)