I'm trying to access the like count and comments of specific shares from Facebook.
Suggest me some method to retrieve the like count and `comments of that.
Now i am getting post id for specific share....
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
#"http://samples.ogp.me/XXXXXXXXXX", #"object",
nil
];
[FBRequestConnection startWithGraphPath:#"/me/og.likes"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(
FBRequestConnection *connection,
id result,
NSError *error
) {
}];
But i am not getting any response for it
Please help me...
I usually use this solution to get likes count:
NSString *likesRequestURL = [[NSString stringWithFormat:#"https://graph.facebook.com/fql?q=SELECT+total_count,+url+FROM+link_stat+WHERE+url+=\"%#\"&access_token=%#", URL, FBSession.activeSession.accessTokenData.accessToken ? FBSession.activeSession.accessTokenData.accessToken : self.fbToken] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:likesRequestURL]
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:60.0f];
__block NSString *result = [NSString string];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error == nil) {
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
SBJsonParser *jsonParser = [[[SBJsonParser alloc] init] autorelease];
result = [NSString stringWithFormat:#"%#", [[[[jsonParser objectWithString:jsonString] objectForKey:#"data"] objectAtIndex:0] objectForKey:#"total_count"]];
[jsonString release];
} else {
NSLog(#"Error = %#", error);
}
}];
It works.
P.S.: I used SBJSONParser, but if you want to use some other, just change corresponding code, it's easy.
Related
I'm trying to change allow a cancellation, future order, and food preparation time through an Asynchronous way by using the POST Method.
I'm new to IOS Development, please give clear code and suggestions, heartful thank you whose are helps.
Here I'm code:
Settings.m
-(void) saveButtonPressed
{
lblsaveSucessful.textAlignment=NSTextAlignmentCenter;
lblsaveSucessful.text=#"Sucessfully saved";
[lblsaveSucessful sizeToFit];
[vwSettings addSubview:lblsaveSucessful];
NSLog(#"button exe");
NSURL *url = [NSURL URLWithString:#"https://www.ecloudbiz.com/Services/RestaurantAppService.svc/json/UpdateGeneralSettings?APIKEY=cbe55b66-0987-4cd4-81e9-73ae18888b9c"];
urlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSMutableURLRequest *request=[[NSMutableURLRequest alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (!error) {
//NSLog(#"Error,%#", [error localizedDescription]);
NSString *string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"%#", string);
NSError *jsonError = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
NSMutableData *postBody=[NSMutableData data];
//Convert the String to Data
[postBody appendData:[[NSString stringWithFormat:#"{\"GeneralSettings\":{\"AllowCancellation\":\"%d\",\"AllowFutureOrder\":\"%d\",\"AppId\":\"7258400b-fec8-4399-9c6c-dce6752ffbf7\",\"AutoCompleteOrders\":\"true\",\"FoodPreparationTime\":\"%#\",\"FoodPreparationTimeType\":\"Minutes\",\"CreatedUser\":\"98eca785-4f90-48f4-8543-23e835f76101\",\"CancellationTime\":\"10 Minutes\",\"LocationId\":\"8652f07c-b2d1-4d2b-aa0f-591e60dca21c\",\"MoreItems\":\"0\",\"OrdersMadeUpto\":\"90 Days\",\"ItemProcessingMinutes\":\"10\",\"ReceiveCancelOrderEmail\":\"true\",\"ReceiveCancelOrderNotification\":\"true\",\"ReceiveCancelOrderText\":\"true\",\"Taxlabel\":\"Sales Tax\",\"Tax\":\"5.8\",\"TakeOutorders\":\"true\",\"DeliveryOrders\":\"true\",\"CateringOrders\":\"true\",\"GuestCheckout\":\"true\"}}",Alwcncl,Alwfuture,txtFp.text]dataUsingEncoding:NSUTF8StringEncoding]];
//Apply the data to the body
[request setHTTPBody:postBody];
NSString *TotalSvc=[NSString stringWithFormat:#"%#",[[NSString alloc] initWithData:postBody encoding:NSUTF8StringEncoding]];
NSLog(#"%#", TotalSvc);
}
else {
//NSLog(#"%#", [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
}
}];
The screen looks below:
enter image description here
settings page
i use this method to save user informations in data base. Can someone help me to upload image too in the same function ?
- (void)Inscription:(NSArray *)value completion:(void (^)( NSString * retour))block{
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSArray *Param_header = #[#"username", #"password", #"email",#"first_name", #"last_name"];
// NSArray *Param_value = #[#"ali", #"aliiiiiiii", #"ali.ali#gmail.com",#"ali",#"zzzzz"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"http:// /Messenger/services/messenger_register"]]];
NSString *aa=[self buildParameterWithPostType:#"User" andParameterHeaders:Param_header ansParameterValues:value];
[request setHTTPBody:[aa dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:#"POST"];
[NSURLConnection sendAsynchronousRequest: request
queue: queue
completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error) {
if (error || !data) {
// Handle the error
NSLog(#"Server Error : %#", error);
} else {
NSError *error = Nil;
id jsonObjects = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
block([NSString stringWithFormat:#"%#", [jsonObjects objectForKey:#"message"]]);
}
}
];
}
You can use third-party frameworks like AFN to upload image。
Here is sample code:
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[#"username"] = #"Jack";
[mgr POST:#"http:// /Messenger/services/messenger_register" parameters:params
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSString *file = [[NSBundle mainBundle] pathForResource:#"image.png" ofType:nil];
NSData *data = [NSData dataWithContentsOfFile:file];
[formData appendPartWithFileData:data name:#"file" fileName:#"image.png" mimeType:#"mage/png"];
}
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"upload success!----%#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"upload failed!----%#", error);
}];
Here's the method that's giving me an error when I compile (see the requestMainPage method)
- (void)loginToMistarWithPin:(NSString *)pin password:(NSString *)password success:(void (^)(void))successHandler failure:(void (^)(void))failureHandler {
NSURL *url = [NSURL URLWithString:#"https://mistar.oakland.k12.mi.us/novi/StudentPortal/Home/Login"];
//Create and send request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
NSString *postString = [NSString stringWithFormat:#"Pin=%#&Password=%#",
[self percentEscapeString:pin],
[self percentEscapeString:password]];
NSData * postBody = [postString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:postBody];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse
*response, NSData *data, NSError *error)
{
// do whatever with the data...and errors
if ([data length] > 0 && error == nil) {
NSError *parseError;
NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (responseJSON) {
// the response was JSON and we successfully decoded it
NSLog(#"Response was = %#", responseJSON);
// assuming you validated that everything was successful, call the success block
if (successHandler)
successHandler();
} else {
// the response was not JSON, so let's see what it was so we can diagnose the issue
NSString *loggedInPage = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response was not JSON (from login), it was = %#", loggedInPage);
if (failureHandler)
failureHandler();
}
}
else {
NSLog(#"error: %#", error);
if (failureHandler)
failureHandler();
}
}]; }
- (NSData *)requestMainPage {
NSData *returner;
//Now redirect to assignments page
NSURL *homeURL = [NSURL URLWithString:#"https://mistar.oakland.k12.mi.us/novi/StudentPortal/Home/PortalMainPage"];
NSMutableURLRequest *requestHome = [[NSMutableURLRequest alloc] initWithURL:homeURL];
[requestHome setHTTPMethod:#"GET"]; // this looks like GET request, not POST
[NSURLConnection sendAsynchronousRequest:requestHome queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *homeResponse, NSData *homeData, NSError *homeError) //Error is in this line.
{
// do whatever with the data...and errors
if ([homeData length] > 0 && homeError == nil) {
NSError *parseError;
NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:homeData options:0 error:&parseError];
if (responseJSON) {
// the response was JSON and we successfully decoded it
NSLog(#"Response was = %#", responseJSON);
} else {
// the response was not JSON, so let's see what it was so we can diagnose the issue
NSString *homePage = [[NSString alloc] initWithData:homeData encoding:NSUTF8StringEncoding];
NSLog(#"Response was not JSON (from home), it was = %#", homePage);
return homePage;
}
}
else {
NSLog(#"error: %#", homeError);
}
return [NSString stringWithFormat:#"%#", homeData];
}]; }
The error came up when I decided I wanted my method (requestMainPage) to have a return type of NSData * rather then just returning void.
So I'm not sure exactly where the problem is.
I figured out my mistake, you can't return values from inside a block.
So if I remove the return homeError and return [NSString stringWithFormat:#"%#", homeData];, the problems go away and I can compile
I'm trying to parse some text from a JSON-file on my server. There's three different values I'm parsing from the file: "value1":"some_value", "value2":"some_value", "value3":"some_value".
I'm declaring a NSMutableArray called statsHome which I initializing in the viewDidLoad method, like this: statsHome = [[NSMutableArray alloc] init];
The problem is that after I have initialized the array, I need to set up a NSDictionary. And if i would do this in the table view, I would write:
NSDictionary *stats = [self.statshome objectAtIndex:indexPath.row];
But I'm not parsing these values to the table view. I want to parse them to UILabels. So what I tried was to declare new NSUInteger. Because I can't use indexPath.row in the viewDidLoad method. I called it statsIndex.
But when I launch the app it crashes and gives me this error message: Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'
The rest of the code looks like this:
#interface DEMOHomeViewController () {
NSUInteger statsIndex;
}
#end
#implementation DEMOHomeViewController
#synthesize statsHome;
#synthesize twitterFollowers;
#synthesize facebookLikes;
#synthesize instagramFollowers;
- (void)viewDidLoad
{
[super viewDidLoad];
statsHome = [[NSMutableArray alloc] init];
NSDictionary *stats = [self.statsHome objectAtIndex:statsIndex];
value1.text = [stats objectForKey:#"value1"];
value2.text = [stats objectForKey:#"value2"];
value3.text = [stats objectForKey:#"value3"];
NSURL *url1 = [[NSURL alloc] initWithString:#"the-json-file-with-the-values.php/file.json"];
NSURLRequest *request1 = [[NSURLRequest alloc] initWithURL:url1];
AFJSONRequestOperation *operation1 = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
self.statsHome = [[NSArray alloc] initWithArray:JSON];
[self.activityIndicatorView stopAnimating];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
}];
[operation1 start];
}
#end
Error is correct: you are trying to get data from an array before data is set. You should do something like in code below.
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url1 = [[NSURL alloc] initWithString:#"the-json-file-with-the-values.php/file.json"];
NSURLRequest *request1 = [[NSURLRequest alloc] initWithURL:url1];
AFJSONRequestOperation *operation1 = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
[self.activityIndicatorView stopAnimating];
[self updateDataWithJSON:JSON]; // <- Here we will update our data
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
}];
[operation1 start];
}
- (void)updateDataWithJSON:(id)JSON
{
self.statsHome = [[NSArray alloc] initWithArray:JSON];
NSDictionary *stats = [self.statsHome objectAtIndex:statsIndex];
value1.text = [stats objectForKey:#"value1"];
value2.text = [stats objectForKey:#"value2"];
value3.text = [stats objectForKey:#"value3"];
}
Let me give you an advice. Seems like your statsIndex initialised in other part of your app. In this case it's better to check if statsIndex is suitable for array length every time you access this array. Otherwise it could be a reason of app crash in some cases: For example you got your array in other controller and it has 10 elements. You select last element but reload a request in your viewDidLoad of DEMOHomeViewController. And in this time array has only 9 elements (last element was deleted already by someone else). -> Crash
NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:#"url"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", #"usernmae", #"password"];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodedStringWithOptions:0]];
NSLog(#"%#",authValue);//
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[request setURL:url];
NSLog(#"%#",url);
NSError *error;
NSHTTPURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code: %ld", (long)[response statusCode]);
NSLog(#"Data is %#",data);
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];