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
Related
I am getting the JSON back that I need, then I segue to another view controller to populate the data into a table view. The data populates, but the app crashes 2 minutes later with a data parameter is nil error.
Is there a way for me to stop the session from running after it completes? It appears to keep running non stop.
My header and implementation file code on pasteBin: https://pastebin.com/M11EF7Yp
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSDictionary *body = #{#"search": self.searchBar.text};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *url = #"https://iosdevfitbody.herokuapp.com/fitbodylocations/search.json";
NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:#"POST" URLString:url parameters:nil error:nil];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
if ([responseObject isKindOfClass:[NSDictionary class]]) {
self.results = [[NSMutableArray alloc] initWithArray:[responseObject objectForKey: #"message"]];
}
} else {
NSLog(#"Error: %#, %#, %#", error, response, responseObject);
}
}]resume];
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSOperationQueue *downloadOperationQueue = [[NSOperationQueue alloc] init];
[downloadOperationQueue cancelAllOperations];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:Url]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSLog(#"Respose %#",response.URL);
NSString *jsonInString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"json in string for backend: %#",jsonInString);
[self.delegate responseConnection:data withMethodName:methodName];
if (!error)
{
// did finish logic here, then tell the caller you are done with success
// completion(YES, nil);
}
else
{
// otherwise, you are done with an error
// completion(NO, error);
}
}];
For NSURLSession:
You can use [NSURLSession cancelPreviousPerformRequestsWithTarget:self];
For NSURLConnection also
You can use [NSURLConnection cancelPreviousPerformRequestsWithTarget:self];
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.
I am creating an asynchronous NSURLconnection in a popup view in ios.
To implement the asynchronous NSURLconnection I implement the methods of the NSURLDelegate.
The problem occurs when the user taps outside the popup view and the view is dismissed.
leaving the nsurlconnection callbacks and other actions inside the view incomplete.
How can I assure that the actions inside the popup complete inspite of the dismissal of the view?
I tried putting an activity indicator inside the popup view till the actions are completed, but even then a tap outside the popup view dismisses the view.
I dont want the user to be left with an inactive app till actions are completed, instead I want the actions to be completed in the background.
If you want to send an asynchronous connection you can use this methods.
GET REQUEST
-(void)placeGetRequest:(NSString *)action withHandler:(void (^)(NSURLResponse *response, NSData *data, NSError *error))ourBlock {
NSString *url = [NSString stringWithFormat:#"%#/%#", URL_API, action];
NSURL *urlUsers = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:urlUsers];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock];
}
POST REQUEST
-(void)placePostRequest:(NSString *)action withData:(NSDictionary *)dataToSend withHandler:(void (^)(NSURLResponse *response, NSData *data, NSError *error))ourBlock {
NSString *urlString = [NSString stringWithFormat:#"%#/%#", URL_API, action];
NSLog(urlString);
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// Creamos el JSON desde el data
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dataToSend options:0 error:&error];
NSString *jsonString;
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *requestData = [NSData dataWithBytes:[jsonString UTF8String] length:[jsonString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock];
}
}
EXAMPLE OF USE
- (void) getMyMethod:(NSString *)myParam1
myParam2:(NSString *)myParam2
myParam3:(NSString *)myParam3
calledBy:(id)calledBy
withSuccess:(SEL)successCallback
andFailure:(SEL)failureCallback{
[self placeGetRequest:[NSString stringWithFormat:#"api/myMethod?myParam1=%#&myParam2=%#&myParam3=%#",myParam1, myParam2, myParam3]
withHandler:^(NSURLResponse *response, NSData *rawData, NSError *error) {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSInteger code = [httpResponse statusCode];
NSLog(#"%ld", (long)code);
if (code == 0){
// error
} else if (!(code >= 200 && code < 300) && !(code == 500)) {
NSString *string = [[NSString alloc] initWithData:rawData
encoding:NSUTF8StringEncoding];
NSLog(#"ERROR (%ld): %#", (long)code, string);
[calledBy performSelector:failureCallback withObject:string];
} else {
// If you receive a JSON
NSMutableDictionary *result = [NSJSONSerialization JSONObjectWithData:rawData options:0 error:nil];
// If you receive an Array
// NSArray *result = [NSJSONSerialization JSONObjectWithData:rawData options:0 error:nil];
// If you receive a string
// NSString *result = [[NSString alloc] initWithData:rawData encoding:NSUTF8StringEncoding];
[calledBy performSelector:successCallback withObject:result];
}
}];
}
CALL YOU MUST DO IN YOUR VIEW/CONTROLLER/ETC
(...)
[api getMyMethod:myParam1Value myParam2:myParam2Value myParam3:myParam3Value calledBy:self withSuccess:#selector(getMyMethodDidEnd:) andFailure:#selector(getMyMethodFailureFailure:)];
(...)
// Don't forget to set your callbacks functions or callbacks will do your app crash
-(void)getMyMethodDidEnd:(id)result{
// your actions with the result
// ...
}
-(void)getMyMethodFailure:(id)result{
// your actions with the result
// ...
}
To prevent the dismissal of popup view when tapping out side u need to implement this delegate method
- (BOOL)popoverControllerShouldDismissPopover:(UIPopoverController *)popoverController
{
return NO;
}
dismiss it by using the action
- (void)someAction
{
//check the operations are completed
.....
.....
[popoverController dismissPopoverAnimated:YES];
}
I am working on one iOS Application, in which i need to post the json web-data to web-service url & base of that i need to get response from server side.
as i have tried to code to send the web-data with json formate but unfortunately yet i haven't got any help to make that possible.
below is the web-url & json request data which i need to pass on web-services to get response,
WebUrl : http://testing.com/controllogic/webservices/all_data_webservice/set_device_token_ios
web data pass : webdata={"device_token":"test"}
now i am confused how i can pass webdata={"device_token":"test"} json post to get response from server side.
below is my code which i have tired to make that possible,
Coding:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSURL *postURL = [NSURL URLWithString: #"http://testing.com/controllogic/webservices/all_data_webservice/set_device_token_ios"];
NSDictionary *jsonDict = [[NSDictionary alloc] initWithObjectsAndKeys:
#"Akash IOS PUSH", #"device_token",
nil];
// NSString *string_val = #"webdata=";
// NSString *data = [NSString stringWithFormat:#"data=%#",[[NSString alloc] initWithData:jsData encoding:NSUTF8StringEncoding]];
// NSString *myString_VAL =[NSString stringWithFormat:#"%#%#",string_val,jsonDict];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: postURL
cachePolicy: NSURLRequestUseProtocolCachePolicy
timeoutInterval: 60.0];
[request setHTTPMethod: #"POST"];
[request setValue: #"application/x-www-form-urlencoded" forHTTPHeaderField: #"Accept"];
[request setValue: #"application/x-www-form-urlencoded" forHTTPHeaderField: #"content-type"];
[request setHTTPBody: jsonData];
[NSURLConnection sendAsynchronousRequest: request
queue: queue
completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error) {
if (error || !data) {
// Handle the error
NSLog(#"Server Error : %#", error);
} else {
// Handle the success
NSLog(#"Server Responce :%#",response);
}
}
];
Please any body help me to make this possible.
You can use following code.I hope this may work.
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys: #"Akash IOS PUSH", #"device_token",nil];
NSData * JsonData =[NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONWritingPrettyPrinted error:nil];
NSString * jsonString= [[NSString alloc] initWithData:JsonData encoding:NSUTF8StringEncoding];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"%#",jsonString] dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://testing.com/controllogic/webservices/all_data_webservice/set_device_token_ios"]]];
[request setHTTPBody:body];
[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 {
// Handle the success
NSLog(#"Server Response :%#",response);
}
}
];