Get all topics the user is subscribed to in Objective-C - ios

I need to get which topics the user subscribe in my app.
I found this question for Android. And try to copy this to Objective-C, but I get an exception:
-(void)getUserTopicSubscribeWithToken
{
NSString *token = [[FIRInstanceID instanceID] token];
NSString *urlString = [NSString stringWithFormat:#"https://iid.googleapis.com/iid/info/<%#>?details=true",token];
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"GET"];
//set the content type to JSON
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"Authorization" forKey:#"FIREBASE_KEY"];
[request setURL:url];
NSError *error = nil;
NSHTTPURLResponse *responseCode = nil;
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];
NSString * topics = [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
NSLog(#"%#",topics);
}
what can be the problem ?

The request does not have any Key called Authorization, I think you mean to say
[request setValue:#"FIREBASE_KEY" forHTTPHeaderField:#"Authorization"];
rather than
[request setValue:#"Authorization" forKey:#"FIREBASE_KEY"];

Related

Unable to post data to WCF service from iPhone

I am trying to post data to WCF service from iPhone Application but somehow service doesn't seems to be call through the iPhone. I received a Status Code = 999.
NSString *urlString = #"http://192.168.1.192/MSservice/SecureRegistration";
NSURL *URL = [NSURL URLWithString:
[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *postData = [bodyData stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned)
{
NSLog(#"Error %#", errorReturned.localizedDescription);
}
else
{
NSLog(#"Data %#", data);
NSString *responseString=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response %#", responseString);
}

Issue with IOS Http POST

Request data
NSDictionary *tmp = #{#"name":#"Kousik",#"age":#"24",#"location":#"bangalore"};
NSString *postdata = [NSString stringWithFormat:#"request = %#",tmp];
//now postdata is
//request = {
"age" = "24";
"location" = "bangalore";
"name" = "Kousik";
}
but I want this NSDictionary should be inside a string so that in server I can eval it and get the dictionary back.
Here I want something like toString() is java or str() in pyhton.
This is my Http request:-
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:path]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *error;
NSData *preparedPostData = [postdata dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postdata length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:preparedPostData ];
[NSURLConnection sendAsynchronousRequest:request
queue:backgroundQueue
completionHandler:^(NSURLResponse response,NSData data,NSError *error){
NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
if(complect)
complect(result,error);
}
];
Update
My request is going to server properly but The problem is with data structure.
when I am trying to access the data with request key then it is giving error because the value for the request key is not supported in server as this value is having = sign in between. So what I want is that to make the requset data structure properly.want to send the NSDictionary itself as a string.
postdata should be something like this
request = "{
age : 24;
location : bangalore;
name : Kousik;
}"
I dont want to use application/json.
NSString *stringURL = [NSString stringWithFormat:#"name=%#&age=%#&location=%#",#"Kousik",#"24",#"bangalore"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",ServerURL,API_SaveContctListToAddressBook]]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[stringURL dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
// NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!data) {
data = [[NSData alloc] init];
}
NSDictionary *dic =[ NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&connectionError];
completionHandler(dic, NO);
}];
Use NSJSONSerialization to convert your dictionary to NSData and then attach it on HTTPBody
NSData *httpBody = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",ServerURL,APIPath]]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:httpBody];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//Handling code
}];

How do I convert this curl command to Objective-C

the command:
curl -X POST -F "search={\"page\":\"1\",\"county\":\"18\",\"type\":\"J\"} " -H "Host: 118932.ro" http://118932.ro/dezv/ipa/index.php
This is what I have so far:
url = [NSURL URLWithString:#"http://www.118932.ro/dezv/ipa/index.php"];
NSData *data = [NSJSONSerialization dataWithJSONObject:self.requestData options:0 error:&error];
NSString *bodyString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSString *dataString = [NSString stringWithFormat:#"\"search=%#\"",bodyString];
NSData *dataBody = [dataString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:dataBody];
[request setValue:#"118932.ro" forHTTPHeaderField:#"Host"];
where self.requestData is the following dictionary
self.requestData = #{#"page" : #"1", #"county" : #"18", #"type" : #"J"};
but this doesnt seem to give me any results after I do this
self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[self.connection start];
Here is the code I use. The -F parameter in cUrl specifies the actual post data, so you may want to use the string "search={\"page\":\"1\",\"county\":\"18\",\"type\":\"J\"} " as is. You should call this code in a background thread as the synchronous call will block the UI.
/**
* Do an HTTP POST request and return the results
*
* #param NSString * url the URL
* #param NSString * post the POST data
*
* #return NSDictionary * a dictionary containing the response, error, and data
*/
+ (NSDictionary *)httpPostRequestWithUrl:(NSString *)url post:(NSString *)post
{
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%d", (int)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[request setTimeoutInterval:30]; // set timeout for 30 seconds
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSMutableDictionary *rc = [[NSMutableDictionary alloc] init];
if ( response )
[rc setObject:response forKey:#"response"];
if ( error )
[rc setObject:error forKey:#"error"];
if ( data )
[rc setObject:data forKey:#"data"];
return (NSDictionary *)rc;
}

How to Use Cache Memory concept in objective-c

// Web service request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: urlLoc]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: requestData];
NSError *respError = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];
//returndata is response of webservice
NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSDictionary *results = [responseString JSONValue] ;
NSLog(#"chat data- %#",results);
NSString *strResults = [results objectForKey:#"d"];
NSLog(#"result string is-%#",strResults);
this is the code that I am using for my Data fetching from web service. But i have to do this every time when come to this page.
Is that any method that can store my data in Cache memory so i need not to request every time.
I Am using
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
but i dont know how to use - (NSCachedURLResponse *) connection this method
thanks...
You need to use cache as of your needs according to this documentation: whenever you requesting a NSMutableURLRequest...
For Ex:
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60];
For More details Kindly look into the Documentation

NSMutableURLRequest transform to ASIFormDataRequest

I have writen the fellowing code:
NSString *urlString = [NSString stringWithFormat:ADDRESS,action];
postStr = #"user_name=Thomas Tan&phone=01234567891&password=123456";
NSData *myRequestData = [NSData dataWithBytes:[postStr UTF8String] length:[postStr length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: myRequestData];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"%#",responseString);
it works well,but now I want to use asihttprequest framework,so how to change the above code,I have writen the code,but it can't get the correct result and just get the server error infomation.so what's the problem?
NSString *urlString = [NSString stringWithFormat:ADDRESS,action];
NSURL *url = [NSURL URLWithString:urlString];
ASIFormDataRequest *requeset = [ASIFormDataRequest requestWithURL:url];
[requeset setRequestMethod:#"POST"];
[requeset setPostValue:#"Thomas Tan" forKey:#"user_name"];
[requeset setPostValue:#"01234567891" forKey:#"phone"];
[requeset setPostValue:#"123456" forKey:#"password"];
[requeset startSynchronous];
NSError *error = [requeset error];
if (!error) {
NSString *re = [requeset responseString];
NSLog(#"%#",re);
}
NSLog(#"%#",error);
thank you in advance.
UPDATE:
NSString *urlString = [NSString stringWithFormat:ADDRESS,action];
NSURL *url = [NSURL URLWithString:urlString];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request appendPostData:[#"user_name=Thomas Tan&phone=01234567891&password=123456" dataUsingEncoding:NSUTF8StringEncoding]];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
NSString *re = [request responseString];
NSLog(#"%#",re);
}
NSLog(#"%#",error);
I use the above code ,It also can't get the same result,and error is not nil.
Your ASIHTTP code is not doing the same thing as your NSURLConnection code.
ASIFormDataRequest will automatically:
set the Content-Type header to application/x-www-form-urlencoded
URL-encoded your parameters
That's usually exactly what you want, but if you're getting the correct behavior with your NSURLConnection code and incorrect with ASIHTTP, then you need to change to a custom ASIHTTP POST and use ASIHTTPRequest, not ASIHTTPFormDataRequest, and then manually set the Conten-type back to application/x-www-form-urlencoded:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request addRequestHeader:#"Content-Type" value:#"application/x-www-form-urlencoded"];
[request appendPostData:[#"user_name=Thomas Tan&phone=01234567891&password=123456" dataUsingEncoding:NSUTF8StringEncoding]];
Doing this, and inspecting exactly what was sent to the server using Wireshark, I can see that the POST data sent is still not quite identical (ASIHTTP on the left, NSURLConnection on the right):
But the content type, length, and actual data is identical.
At this point, I'd expect your server to return the same result.
If it still doesn't, you can edit the ASIhTTP request parameters to match.

Resources