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);
Related
What's an efficient way to take an NSURL object such as the following:
foo://name/12345
and break it up into one string and one unsigned integer, where the string val is 'name' and the unsigned int is 12345?
I'm assuming the algorithm involves converting NSURL to an NSString and then using some components of NSScanner to finish the rest?
I can only add an example here, the NSURL class is the one to go. This is not complete but will give you a hint on how to use NSURL:
NSString *url_ = #"foo://name.com:8080/12345;param?foo=1&baa=2#fragment";
NSURL *url = [NSURL URLWithString:url_];
NSLog(#"scheme: %#", [url scheme]);
NSLog(#"host: %#", [url host]);
NSLog(#"port: %#", [url port]);
NSLog(#"path: %#", [url path]);
NSLog(#"path components: %#", [url pathComponents]);
NSLog(#"parameterString: %#", [url parameterString]);
NSLog(#"query: %#", [url query]);
NSLog(#"fragment: %#", [url fragment]);
output:
scheme: foo
host: name.com
port: 8080
path: /12345
path components: (
"/",
12345
)
parameterString: param
query: foo=1&baa=2
fragment: fragment
This Q&A NSURL's parameterString confusion with use of ';' vs '&' is also interesting regarding URLs.
NSURL has a method pathComponents, which returns an array with all the different path components. That should help you get the integer part. To get the name I'd use the host method of the NSURL. The docs say, that it should work if the URL is properly formatted, might as well give it a try then.
All in all, no need to convert into a string, there seems to be plenty of methods to work out the components of the URL from the NSURL object itself.
Actually there is a better way to parse NSURL. Use NSURLComponents. Here is a simle example:
Swift:
extension URL {
var params: [String: String]? {
if let urlComponents = URLComponents(url: self, resolvingAgainstBaseURL: true) {
if let queryItems = urlComponents.queryItems {
var params = [String: String]()
queryItems.forEach{
params[$0.name] = $0.value
}
return params
}
}
return nil
}
}
Objective-C:
NSURLComponents *components = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
NSArray *queryItems = [components queryItems];
NSMutableDictionary *dict = [NSMutableDictionary new];
for (NSURLQueryItem *item in queryItems)
{
[dict setObject:[item value] forKey:[item name]];
}
Thanks to Nick for pointing me in the right direction.
I wanted to compare file urls but was having problems with extra slashes making isEqualString useless. You can use my example below for comparing two urls by first de-constructing them and then comparing the parts against each other.
- (BOOL) isURLMatch:(NSString*) url1 url2:(NSString*) url2
{
NSURL *u1 = [NSURL URLWithString:url1];
NSURL *u2 = [NSURL URLWithString:url2];
if (![[u1 scheme] isEqualToString:[u2 scheme]]) return NO;
if (![[u1 host] isEqualToString:[u2 host]]) return NO;
if (![[url1 pathComponents] isEqualToArray:[url2 pathComponents]]) return NO;
//check some properties if not nil as isEqualSting fails when comparing them
if ([u1 port] && [u2 port])
{
if (![[u1 port] isEqualToNumber:[u2 port]]) return NO;
}
if ([u1 query] && [u2 query])
{
if (![[u1 query] isEqualToString:[u2 query]]) return NO;
}
return YES;
}
(iOS 8.0+)
I want to use NSURL to pass some parameters in query part, like this:
NSURLComponents *components = [[NSURLComponents alloc] initWithString:#"ft://market/detail"];
NSDictionary *parameters = #{#"username" : #"高高高", #"from" : #"中国北京"};
NSMutableArray *items = [[NSMutableArray alloc] init];
for (NSString *key in parameters.allKeys) {
[items addObject:[[NSURLQueryItem alloc] initWithName:key value:parameters[key]]];
}
components.queryItems = items;
NSURL *url = components.URL;
NSLog(#"url : %#", url);
However, when I receive the URL and parse it, I find that the Chinese characters passed in the query part are abnormal, and I used NSURLComponents to parse the URL like this:
NSURLComponents *anaComponents = [NSURLComponents componentsWithString:url.absoluteString];
NSMutableDictionary *queryParams = [[NSMutableDictionary alloc] init];
for (NSURLQueryItem *querItem in anaComponents.queryItems) {
[queryParams setObject:querItem.value forKey:querItem.name];
}
NSLog(#"queryParams : %#", queryParams);
The following is the debug log:
url : ft://market/detail?username=%E9%AB%98%E9%AB%98%E9%AB%98&from=%E4%B8%AD%E5%9B%BD%E5%8C%97%E4%BA%AC
queryParams : {
from = "\U4e2d\U56fd\U5317\U4eac";
username = "\U9ad8\U9ad8\U9ad8";
}
The problem now seems to be that there is a problem with encoding and decoding of characters such as Chinese, even if [parameters[key] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]] method is used to encode the query value, it is still wrong when decoding.
The query part I want to parse is like this : #{#"username" : #"高高高", #"from" : #"中国北京"};.
Hope for your helps here, Thanks sincerely.
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]];
I am receiving comma separated string as below which is to be converted to array of dictionaries.I tried using [myString componentsSeparatedByString:#","]; which however gives a totally different output.What is the correct way of converting it?
NSString *cancellationStr ==> [{"cutoffTime":"0-2","refundInPercentage":"0"},{"cutoffTime":"2-3","refundInPercentage":"50"},{"cutoffTime":"3-24","refundInPercentage":"90"}]
NSArray *array = [cancellationStr componentsSeparatedByString:#","];
//Gives response like below
(
"[{\"cutoffTime\":\"0-2\"",
"\"refundInPercentage\":\"0\"}",
"{\"cutoffTime\":\"2-3\"",
"\"refundInPercentage\":\"50\"}",
"{\"cutoffTime\":\"3-24\"",
"\"refundInPercentage\":\"90\"}]"
)
The code to fetch and parse using a singleton HTTP class
NSString *urlString=[NSString stringWithFormat:#"%#%#sourceCity=%#&destinationCity=%#&doj=%#",BASE_URL,AVAILABLE_BUSES,source,destination,dateStr];
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url= [NSURL URLWithString:urlString];
SuccessBlock successBlock = ^(NSData *responseData){
NSError *error;
jsonDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
bArray = [jsonDictionary objectForKey:#"apiAvailableBuses"];
};
FailureBlock failureBlock = ^(NSError *error){
NSLog(#"%#",error);
};
HTTPRequest *request = [[HTTPRequest alloc]initWithURL:url successBlock:successBlock failureBlock:failureBlock];
[request startRequest];
The above success block receives the string which then I am looking to convert.
NSString *cancellationStr = [[bArray objectAtIndex:rowIndex]valueForKey:#"cancellationPolicy"];
bObject.cancellationPolicy = [cancellationStr componentsSeparatedByString:#","];
NSLog(#"Cancellation Array : %#",bObject.cancellationPolicy);
So, "apiAvailableBusses" is an array of elements like this one:
{
"operatorId":196,
"operatorName":"Sahara Bus",
"departureTime":"6:45 PM",
"mTicketAllowed":false,
"idProofRequired":false,
"serviceId":"1602",
"fare":"450",
"busType":"Sahara Hitech Non A/c",
"routeScheduleId":"1602",
"availableSeats":29,
"partialCancellationAllowed":false,
"arrivalTime":"07:30 AM",
"cancellationPolicy":"[{\"cutoffTime\":\"12\",\"refundInPercentage\":\"0\"},{\"cutoffTime\":\"24\",\"refundInPercentage\":\"50\"}]",
"commPCT":0.0,
"boardingPoints":[
{
"time":"09:05PM",
"location":"Ameerpet,Kaveri Kmakshi Travels,Beside RKS Mall,Ameerpet, Mr.Aman-9391830030.",
"id":"6"
},
{
"time":"09:15PM",
"location":"Punjagutta,Sai Ganesh Travels, Punjagutta, Mr.Aman-9391830030.",
"id":"2241"
},
{
"time":"09:30PM",
"location":"Lakdi-ka-pool,Sahara Travels,Hotel Sri Krishna Complex,Mr.Aman-9391830030.",
"id":"2242"
},
{
"time":"08:45PM",
"location":"ESI,Behind Bajaj Show Room, Near Nani Travels. Mr.Aman-9391830030.",
"id":"2287"
},
{
"time":"09:45PM",
"location":"Nampally,Near Khaja Travels, Nampally,Mr.Aman-9391830030.",
"id":"2321"
},
{
"time":"09:16PM",
"location":"Paradise,Near SVR Travels, Paradise,Mr.Aman-9391830030.",
"id":"2322"
},
{
"time":"10:00PM",
"location":"Afzalgunj,Sahar Travels,Mr.Aman-9391830030.",
"id":"2323"
},
{
"time":"09:00PM",
"location":"Secunderbad Station,Near Asian Travels.Mr.Aman-9391830030.",
"id":"2336"
}
],
"droppingPoints":null,
"inventoryType":0
}
The "cancellationPolicy" element is a string which is what is called "embedded JSON". (Why they did that in this case I haven't a clue.) This means that the string must be fed through NSJSONSerialization again. And to convert the NSString to NSData (to feed through NSJSONSerialization again) you need to first use dataWithEncoding:NSUTF8StringEncoding.
my url is https://photos.googleapis.com/data/upload/resumable/media/create-session/feed/api/user/111066158452258/albumid/60281009241807
i want to extract the value of user & albumid, i had tried to extract with different methods which i found in stack overflow ,but they didn't work.
Please help me out.
Thank you for your precious time.
You can take your NSURL (or init one from the URL string), and use the method pathComponents which return an array of the words in the URL (separated from the slash /), so:
pathComponents[0] == #"photos.googleapis.com"
pathComponents[1] == #"data"
...etc.
Here the snippet of code:
NSURL *url = [NSURL urlWithString:#"https://photos.googleapis.com/data/upload/resumable/media/create-session/feed/api/user/111066158452258/albumid/60281009241807"];
NSString *user = url.pathComponents[9];
NSString *album = url.pathComponents[11];
I give you an example here, NSURL class is your friend. You can use e.g. pathComponents: to get an array of all components and then process this array as you need it:
NSURL *url = [NSURL URLWithString:#"https://photos.googleapis.com/data/upload/resumable/media/create-session/feed/api/user/111066158452258/albumid/60281009241807"];
NSArray *components = [url pathComponents];
NSLog(#"path components: %#", components);
NSLog(#"user: %#", components[9]);
NSLog(#"albumid: %#", components[11]);
NSURL *url = [NSURL URLWithString:#"https://photos.googleapis.com/data/upload/resumable/media/create-session/feed/api/user/111066158452258/albumid/60281009241807"];
NSArray *pathComponentsArray = [url pathComponents];
NSString*userValue;
NSString*albumidValue;
for(int i=0;i<[pathComponentsArray count];i++)
{
if([pathComponentsArray[i] isEqualToString:#"user"])
{
userValue = pathComponentsArray[i+1];
}
if([pathComponentsArray[i] isEqualToString:#"albumid"])
{
albumidValue = pathComponentsArray[i+1];
}
}