Spinning Bar Using AFNetworking - objective-c

I have this method that is reaching a webservice and bring me back a JSON. The method is working fine, the problem is that I want a spinning bar progress while this method is not bringing anything yet.
-(void)loadJson{
NSString *urlString = [NSString stringWithFormat:#"%#",kGetURL];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
self.json = JSON;
[myTableView reloadData];
} failure:^(NSURLRequest *request , NSURLResponse *response , NSError *error , id JSON){
NSLog(#"Failed: %#",[error localizedDescription]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"didn't reach the server"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
}];
[operation start];
}
thank you.

Create a UIActivityIndicatorView, here called mySpinner, and add it to the screen. Then:
-(void)loadJson{
NSString *urlString = [NSString stringWithFormat:#"%#",kGetURL];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
[mySpinner stopAnimating];
self.json = JSON;
[myTableView reloadData];
} failure:^(NSURLRequest *request , NSURLResponse *response , NSError *error , id JSON){
[mySpinner stopAnimating];
NSLog(#"Failed: %#",[error localizedDescription]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"didn't reach the server"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
}];
mySpinner.hidesWhenStopped = YES;
[mySpinner startAnimating];
[operation start];
}

Related

UITextField keyboard pop up after api response received

In my app am using UITextField in the login screen. To get the login details I connect the app to server through API. While calling the api I display an activity UIActivityIndicatorView. Before calling the api I do end editing. once the response is received from server again the keyboard is pop up when the activity indicator stops
Here is my Code
[self.view endEditing:YES];
VW_overlay.hidden = NO;
[activityIndicatorView startAnimating];
[self performSelector:#selector(API_Login) withObject:activityIndicatorView afterDelay:0.01];
and the API_Login Method have the following code
-(void) API_Login
{
NSString *userEmail = _TXT_email.text;
NSString *userPWD = _TXT_password.text;
NSError *error;
NSHTTPURLResponse *response = nil;
NSString *post = [NSString stringWithFormat:#"username=%#&password=%#",userEmail,userPWD];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSString *urlGetuser =[NSString stringWithFormat:#"%#loginApi",SERVER_URL];
NSURL *urlProducts=[NSURL URLWithString:urlGetuser];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:urlProducts];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[request setHTTPShouldHandleCookies:NO];
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (aData)
{
NSMutableDictionary *json_DATA = (NSMutableDictionary *)[NSJSONSerialization JSONObjectWithData:aData options:NSASCIIStringEncoding error:&error];
NSLog(#"The response %#",json_DATA);
if ([[json_DATA valueForKey:#"status"]isEqualToString:#"success"]) {
[[NSUserDefaults standardUserDefaults] setValue:[json_DATA valueForKey:#"driver_id"] forKey:#"driver_id"];
[[NSUserDefaults standardUserDefaults] synchronize];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[json_DATA valueForKey:#"status"] message:[json_DATA valueForKey:#"msg"] delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok", nil];
[alert show];
[activityIndicatorView stopAnimating];
VW_overlay.hidden = YES;
[self performSelector:#selector(stop_activity) withObject:nil afterDelay:1.0];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[json_DATA valueForKey:#"status"] message:[json_DATA valueForKey:#"msg"] delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok", nil];
[alert show];
}
}
else
{
[activityIndicatorView stopAnimating];
VW_overlay.hidden = YES;
NSLog(#"Error %#\nResponse %#",error,response);
}
}
-(void) stop_activity
{
[self order_details_page];
}
-(void)order_details_page
{
[self performSegueWithIdentifier:#"login_order" sender:self];
}

How to upload UIImage from iOS to Azure storage

I try to upload an image to Azure storage through MVC 4 web API. But the server side always return:
"Invalid length for a Base-64 char array or string."
Below is Objective-C code:
- (IBAction)btnUploadReceipt:(id)sender {
UIImage *img = self.imgReceipt.image;
NSData *dataObj = UIImagePNGRepresentation(img);
NSString *fff = [dataObj base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
//NSString *ddd = [self base64EncodeString:imgData];
//NSString *ddd = [dataObj base64EncodedString];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/api/upload/UploadAzure",baseUrl]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"Post"];
NSString *jsonData = [NSString stringWithFormat:#"FileName=%#&FileData=%#&FolderName=%#&UserName=%#&Point=%#&DateTime=%#&MerchantName=%#&OutletID=%#",fileName,fff,imgFolder,userName,#"3",dateTime,_mName,_mOutletID];
[request setHTTPBody:[jsonData dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
if (data.length > 0 && connectionError == nil)
{
NSString * json =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#",json);
if ([json isEqualToString:#"\"True\""]) {
NSLog(#"%#",#"Success Add Photo");
//[self dismissViewControllerAnimated:YES completion:nil];
//[[self navigationController]popViewControllerAnimated:YES];
}
else
{
UIAlertView *messageAlert = [[UIAlertView alloc]initWithTitle:#"Connection Error" message:#"Please Check Internet Setting" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[messageAlert show];
}
}
else
{
UIAlertView *messageAlert = [[UIAlertView alloc]initWithTitle:#"Connection Error" message:#"Please Check Internet Setting" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[messageAlert show];
}
}];
}
- (NSString *)base64String2 {
UIImage *img = self.imgReceipt.image;
NSData * data = [UIImagePNGRepresentation(img) base64EncodedDataWithOptions:NSDataBase64Encoding64CharacterLineLength];
return [NSString stringWithUTF8String:[data bytes]];
}
Anyone face this kind of problem?
Have you tried using the Azure Storage iOS Library? The Getting Started documentation should be able to help with your scenario.

AFNetworking JSON Request, neither success nor error block called

I'm trying to learn AFNetworking so have written a simple block. I'm trying to retrieve & log the json from the site url below.
NSString *string =
#"http://transportapi.com/v3/uk/bus/stop/490012745J/live.json?api_key=6ee115459cbeccdb902b14d39b61330d&app_id=9deefeb1&group=route";
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *mydict = (NSDictionary *)responseObject;
NSString *key;
for(key in mydict){
NSLog(#" key %#", key);
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"ERROR");
}];
But neither the success or the failure block is being called. Can someone point out what I've done wrong?
You're not actually firing the operation you need to add
[[NSOperationQueue mainQueue] addOperation:operation];

Parsing Json to handle and direct a user to view controller. Objective C

I have a Login screen and I POST username and password to a login page.
The webservice gives me 2 responses if the Login user details are correct I get a response of back from the request.
{"value":1}
and if the user details are wrong I get back from request.
{"value":0}
I have been able to parse that JSON Result to give me a log output of
value: 1 or value:0
I am battling to handle the parsed json e.g
//parse out the json data
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:urlData //1
options:kNilOptions
error:&error];
NSArray* defineJsonData = [json objectForKey:#"value"]; //2
NSLog(#"value: %#", defineJsonData); //3
if ([[json objectForKey:#"value"] isEqualToNumber:[NSNumber numberWithInt:1]])
{
HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"37x-Checkmark.png"]];
HUD.mode = MBProgressHUDModeCustomView;
[HUD hide:YES afterDelay:0];
[self performSegueWithIdentifier: #"introScreenView" sender:self];
}
else {
HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"37x-Checkmark.png"]];
HUD.mode = MBProgressHUDModeCustomView;
[HUD hide:YES afterDelay:0];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Wrong Credentials" message:#"Please try to login again" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
Here is the rest of my code.
- (void)myTask {
if ([userNameTextField.text isEqualToString:#""] || [passwordTextField.text isEqualToString:#""]) {
HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"37x-Checkmark.png"]];
HUD.mode = MBProgressHUDModeCustomView;
[HUD hide:YES afterDelay:0];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Feilds Missing" message:#"Please Fill all the field" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
return;
}
NSString *data = [NSString stringWithFormat:#"UserName=%#&Password=%#",userNameTextField.text, passwordTextField.text];
NSData *postData = [data dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
// preaparing URL request to send data.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSString *url = [NSString stringWithFormat:#"http://www.ddproam.co.za/Central/Account/LogOnIOS?"];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
[request setTimeoutInterval:7.0];
NSURLResponse *response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Login response:%#",str);
NSHTTPCookie *cookie;
NSLog(#"name: '%#'\n", [cookie name]);
for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies])
{
NSLog(#"name: '%#'\n", [cookie name]);
NSLog(#"value: '%#'\n", [cookie value]);
NSLog(#"domain: '%#'\n", [cookie domain]);
NSLog(#"path: '%#'\n", [cookie path]);
}
//parse out the json data
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:urlData //1
options:kNilOptions
error:&error];
NSArray* defineJsonData = [json objectForKey:#"value"]; //2
NSLog(#"value: %#", defineJsonData); //3
if ([defineJsonData isEqual:0])
{
HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"37x-Checkmark.png"]];
HUD.mode = MBProgressHUDModeCustomView;
[HUD hide:YES afterDelay:0];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Wrong Credentials" message:#"Please try to login again" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
else {
HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"37x-Checkmark.png"]];
HUD.mode = MBProgressHUDModeCustomView;
[HUD hide:YES afterDelay:0];
[self performSegueWithIdentifier: #"introScreenView" sender:self];
}
if (theConnection) {
}
}
If response from the server is really just {"value":1}, then you correctly parse JSON to dictionary using NSJSONSerialization.
However under value key, there is an instance of NSNumber, not NSArray.
Your code to retrieve value and check it should look like this:
NSNumber *defineJsonData = [json objectForKey:#"value"];
NSLog(#"value: %#", defineJsonData);
if ([defineJsonData integerValue] == 0) {
NSLog(#"Wrong credentials");
}
else {
NSLog(#"Welcome :-)");
}

POST to web-server in Objective C

I've been working on a way to send a value to a web-server in objective c.
I think I have everything working on both ends, except for the fact that my value doesn't show up in the email that is sent out.
Here is my code, if someone could point out what I'm doing wrong, that would be great.
(dval is what's not showing up)
NSMutableString *mmessage = [[NSMutableString alloc]initWithString:#""];
[mmessage appendString:[NSString stringWithFormat:#"<p><b>Drink Name:</b> %#</p>", dval]];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://test.com/api/stuff/send"]];
NSMutableDictionary *postInfo = [NSDictionary dictionaryWithObject:[NSDictionary dictionaryWithObjectsAndKeys:mmessage, #"message", nil] forKey:#"form"];
NSError *e = nil;
NSData *postData = [NSJSONSerialization dataWithJSONObject:postInfo options:0 error:&e ];
__block int resp_code = 0;
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:urlRequest
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
resp_code = httpResponse.statusCode;
if(resp_code == 200){
NSDictionary *jsonObjects = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
if ([[jsonObjects objectForKey:#"status"] isEqualToString:#"success"]) {
UIAlertView *emailsuccess = [[UIAlertView alloc] initWithTitle:#"Email Successfully sent." message:nil delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[emailsuccess show];
}
else if ([[jsonObjects objectForKey:#"status"] isEqualToString:#"failed"]) {
UIAlertView *emailfailed = [[UIAlertView alloc] initWithTitle:#"Email Failed." message:[jsonObjects objectForKey:#"messages"] delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[emailfailed show];
}
else {
UIAlertView *emailfailed = [[UIAlertView alloc] initWithTitle:#"Email Response." message:[jsonObjects objectForKey:#"messages"] delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[emailfailed show];
}
}
}];