HTTP get method getting empty value - ios

I am using HTTP get method for getting the value from the url, in the url response is getting but for me value is not coming can any one help me. Below is my coding
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.gmasa.org/wp-json/posts?type=owl-carousel&filter[Carousel]=speakers&filter[posts_per_page]=-1"]];
NSURLResponse *requestResponse;
NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)requestResponse;
NSInteger statusCode = [HTTPResponse statusCode];
NSData *requestHandler = [[NSData alloc]init];
requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];
NSLog(#"requestresponce: %#", requestHandler);
NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
for me request handler value is getting this like "<>", whats is the problem.

Get and analyse a connection error if any and response:
NSError *error;
NSData *requestHandler = [[NSData alloc]init];
requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:&error];
NSLog(#"Connection error = %#", error);
NSLog(#"Response = %#", requestResponse);
Without this information it is impossible to determine where is a problem - it could be bad connection, bad URL, back-end issue and so on...

Related

Getting JSON Response issue

Currently i am using .net Api's for getting response
Here is my iOS source code:
-(void)getUserNameFromFacebbok: (NSString*)newUserName withFacebookId: (NSString*)newFbId withFacebookLoginEmailId: (NSString*)newEmailId withProfilePicUrl: (NSString*)newProfilePicUrl{
NSString * fbApiURLStr =[NSString stringWithFormat:#"http://example.com/api/v1/FacebookUserLogin?UserName=%#&id=%#&emailid=%#&facebookurl=%#",
newUserName,
newFbId,
newEmailId,
newProfilePicUrl];
NSMutableURLRequest *dataRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:fbApiURLStr]];
NSHTTPURLResponse *response =[[NSHTTPURLResponse alloc] init];
NSError* error;
NSData *responseData = [NSURLConnection sendSynchronousRequest:dataRequest returningResponse:&response error:&error];
facebookLoginResponseDict = [NSJSONSerialization JSONObjectWithData:responseData
options:0
error:&error];
}
I am not getting any response dataRequest parameter ====> currently i am getting { URL: (null) }
Can you please help me out how can i solve this issue
Sorry, I found the proper solution like
NSURL *url = [NSURL URLWithString:#"http://example.com/api/v1/FacebookUserLogin?UserName=Brahmam&id=4654566&emailid=ghjnghjnhgh#gmail.com&facebookurl=https://fbjghjghjghjghmkjhgmhjkmhjmh"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response;
NSError *error;
//send it synchronous
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// check for an error. If there is a network error, you should handle it here.
if(!error)
{
//log response
NSLog(#"Response from server = %#", responseString);
}

Sometimes login will take long time

I am new in iOS application development. I have one problem in login page.
Sometimes it will take long time for log in. I am using this code to send or receive a request from a httpserver.
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonData1
options:0 // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (!jsonData) {
NSLog(#"Got an error: %#", error);
} else {
jsonString= [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"converted json string is %#",jsonString);
}
NSData *postData = [[[NSString alloc] initWithFormat:#"method=methodName&email=%#&password=%#", user_name, pass_word] dataUsingEncoding:NSASCIIStringEncoding ];
NSString *postLength = [NSString stringWithFormat:#"%ld",[postData length]];
jsonData=[jsonString dataUsingEncoding:NSASCIIStringEncoding];
NSLog(#"the final passing json data is %#",jsonData);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http:urladdress"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"\"Accept\""];
[request setValue:#"application/json" forHTTPHeaderField:#"\"Content-Type\""];
[request setValue:postLength forHTTPHeaderField:#"\"Content-Length\""];
[request setValue:#"application/x-www-form-urlencoded;" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
NSError *requestError = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&requestError];
//if communication was successful
if ([response statusCode] >= 200 && [response statusCode] < 300) {
NSError *serializeError = nil;
NSString* newStr = [NSString stringWithString :[urlData bytes]];
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:urlData
options:NSJSONReadingAllowFragments
error:&serializeError];
NSLog(#"recdata %#",jsonData);
}
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection)
{
NSLog(#"theConnection is succesful");
self.receivedData = [NSMutableData data];
}
[connection start];
[self readFromDataBase];
if (dataCheck==true) {
[self checkPassword];
}
is there any way to login faster.?
Maybe the connection is slow because your server or your connection quality.
Did you try with async? It won't freeze your app when waiting the respond
Asynchronous NSURLConnection Scheme Tutorial
For your program, replace the sendSync method:
NSData *urlData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&requestError];
by sendAsync method:
NSOperationQueue *mainQueue = [[NSOperationQueue alloc] init];
[mainQueue setMaxConcurrentOperationCount:5];
[NSURLConnection sendAsynchronousRequest:request queue:mainQueue completionHandler:^(NSURLResponse *response, NSData *urlData, NSError *requestError) {
// doing somethings ...
// if communication was successful ...
}];

Feedly Mark as Read not working on Objective-C

I'm trying to implement a method in my iOS app to mark an article as read using the Feedly API. However, I keep getting error responses:
{
"errorCode": 400,
"errorId": "sandbox-he.2015010906.2770040",
"errorMessage": "no data"
}
This is the method:
- (void)markRead:(NSString*)articleID {
NSLog(#"Artidle ID is: %#", articleID);
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSString *accessToken = [standardUserDefaults objectForKey:#"AccessToken"];
NSString *feedUrl = [NSURL URLWithString:#"https://sandbox.feedly.com/v3/markers"];
NSError *error = nil;
NSString *post =[[NSString alloc] initWithFormat:#"action=markAsRead&type=entries&entryIds=%#",articleID];
NSLog(#"PostData: %#",post);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:feedUrl];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-type"];
[request setHTTPBody:postData];
[request addValue:accessToken forHTTPHeaderField:#"Authorization"];
//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *errror = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&errror];
NSLog(#"Response code: %ld", (long)[response statusCode]);
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSLog(#"Success marking this as read.");
} else {
if (error) NSLog(#"Error: %#", errror);
NSLog(#"No success marking this as read.");
}
}
The Feedly API describes that it requires this as input:
{
"entryIds": [
"TSxGHgRh4oAiHxRU9TgPrpYvYVBPjipkmUVSHGYCTY0=_14499073085:c034:d32dab1f",
"TSxGHgRh4oAiHxRU9TgPrpYvYVBPjipkmUVSHGYCTY0=_1449255d60a:22c3491:9c6d71ab"
],
"action": "markAsRead",
"type": "entries"
}
In my opinion I'm providing this as input, so I actually expected a proper response. However, I keep getting 400 and can't seem to figure out what I'm doing wrong. I've been busting my head for hours on this.
Instead of using your current body data, try creating the data with following code:
NSDictionary *bodyDict = [NSDictionary dictionaryWithObjectsAndKeys:#[articleID],#"entryIds",
#"markAsRead",#"action",
#"entries",#"type", nil];
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:bodyDict options:0 error:&error];
[request setHTTPBody:postData];
This will send the body as a JSON object.
Sending parameter like you did (with action=markAsRead&type=entries&entryIds=%#) is usually used when calling a web method with the GET request method. Take a look at POST vs GET for a better understanding.

Proper JSON encoding for HTTP POST request in iOS

Posted a query previously about JSON parsing not working properly. Did more looking into it with a packet sniffer and also with another client that works properly and found out it's a syntax thing, that I still can't seem to solve.
The code in the bottom makes the HTTP request to have the JSON in it as:
{"key":"value"}
And my server is actually looking for a JSON in the following syntax:
key=%22value%22
I tried to write some code that does this manually, but figured there must be something out of the box for iOS, and I don't want to have faults in the future.
I messed around with it for a while trying to find the right code for the job, but couldn't (you can see some code I tried commented out). Can anyone help me?
+ (NSString*)makePostCall:(NSString*)urlSuffix
keys:(NSArray*)keys
objects:(NSArray*)objects{
NSDictionary *params = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
// NSString *dataString = [self getDataStringFromDictionary:params];
// NSData *jsonData = [dataString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
options:0
error:&error];
// id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
// NSLog(#"%#", jsonObject);
if (!jsonData) {
// should not happen
NSError *error;
NSLog(#"Got an error parsing the parameters: %#", error);
return nil;
} else {
// NSString *jsonRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// NSLog(#"%#", jsonRequest);
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#", urlPrefix, urlSuffix]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
// NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
// [request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: jsonData];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
// TODO: handle error somehow
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return returnString;
}
}

Extract data from NSURLResponse

I have this sweet method that authenticates a user, however I can't figure out how to get the status code of the request. I can clearly see it exists when I do NSLog(#"%#", response);, but I can't find any way to pull it out of that. Is there a method or do I have to parse it myself somehow?
- (BOOL)authenticateUserWithEmail:(NSString *)email password:(NSString *)password
{
NSURL *url = [[NSURL alloc] initWithString:[NSString stringWithFormat:
#"%#/users/sign_in.json?user[email]=%#&user[password]=%#&user[remember_me]=true",
LURL,
email,
password]];
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:url];
[urlRequest setHTTPMethod:#"POST"];
NSURLResponse *response;
NSError *error;
NSData *responseData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
NSLog(#"Response: %#", [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding] );
NSLog(#"Response Meta: %#", response);
return (error == NULL);
}
Try this
NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
NSInteger statusCode = [HTTPResponse statusCode];

Resources