Showing posts with label Objective C. Show all posts
Showing posts with label Objective C. Show all posts

Monday, 13 February 2017

Mobile and Web Client sample code with OAuth2.0 | Symfony 2 RESTful API Project with FOSUserBundle, FOSRestBundle, FOSOAuthServerBundle

OAuth is an open standard for authorization. It provides client application secure access to server resources on behalf of resource owner.

OAuth2.0 focuses on client developer simplicity while providing specific authorization flows for web, desktop applications and mobile devices.


Here is the complete guide documentation process and demo example for Mobile and Web Client:

 AJOAuth2 - iOS

MSOAuth2 - Android

authOauth - Symfony2

Above sample code on different platforms are showing the process of authenticating against an OAuth 2 provider.


Cheers!!
~ Nerd Team


Saturday, 20 February 2016

Geocoding Google map in iOS

#define GEOCODING_URI @"https://maps.googleapis.com/maps/api/geocode/json?key=&language=en-US&sensor=true&address=" // TODO: add DEV_KEY for Geocoding
NSString *actionURI = [NSString stringWithFormat:@"%@%@",GEOCODING_URI, self.geocodeTextField.text];
NSLog(@"ACTION URL: %@",actionURI);
NSString *encodedURI = [actionURI stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager*manager = [AFHTTPRequestOperationManager manager];
[manager GET:encodedURI parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject); 
NSDictionary *jsonDict = (NSDictionary *)responseObject;
if (!jsonDict)
   return;
if ([jsonDict isKindOfClass:[NSDictionary class]] == NO)
   NSAssert(NO, @"Expected a dictionary, got %@", NSStringFromClass([jsonDict class]));     
if ([jsonDict[@"status"] isEqualToString:@"OK"]) {
    NSArray *locGeometryResult=[[jsonDict valueForKeyPath:@"results.geometry"] objectAtIndex:0];
    NSDictionary *locationDict = [locGeometryResult valueForKey:@"location"];
    NSLog(@"JSON: %@", locationDict.description);
    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake([locationDict[@"lat"] doubleValue], [locationDict[@"lng"] doubleValue]);
    GMSCameraUpdate *updatedCamera = [GMSCameraUpdate setTarget:coordinate zoom:17];
    [self.mapView animateWithCameraUpdate:updatedCamera];
} else {
        NSLog(@"No location found.");
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@"); 
}];

Thursday, 16 August 2012

Add Minutes | Hours | Days to NSDate


NSDate *date = [NSDate date];
NSTimeInterval timeInterval = YOUR_DOUBLE_VALUE;
NSLog(@"Time Interval : %.2f", timeInterval);
date = [date dateByAddingTimeInterval:timeInterval];
NSLog(@"Date : %@",date);

For Minutes : +/-(no.of mins * 60);
For Hours : +/-(no. of hrs * 60 * 60);
For days : +/-(no. of days * 60 * 60 * 24);
+ sign for add.
- sign for subtract.
Both will work.

NSTimeInterval accepts double value.

Tuesday, 24 April 2012

iPhone | UIButton set title label, font, alignment

     
UIButton *yourButton = [UIButtonbuttonWithType:UIButtonTypeCustom];
yourButton.frame=CGRectMake(X_ORIGIN,Y_ORIGIN,WIDTH,HEIGHT);
// Here, yourButton.titleLabel.text = @"YOUR_TEXT"; // doesn't do the trick :(
[yourButton setTitle:@"YOUR_TEXT" forState:UIControlStateNormal];
[yourButton addTarget:self action:@selector(YOUR_SELECTOR) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview: yourButton];

However, I'm not sure why yourButton.titleLabel.text = @"YOUR_TEXT";  doesn't work
[yourButton setTitle:@"YOUR_TEXT" forState:UIControlStateNormal]; did the trick though!

if you change the font of this title :
yourButton.titleLabel.font = YOUR_FONT_VALUE;

if you change the alignment-left of UIButton :
yourButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
adjustment of content left inset , otherwise text will touch the left border.
yourButton.contentEdgeInsets = UIEdgeInsetsMake(0,10,0,0);

Note: Check out UIControl API docs.

Hope it makes life easier!

Friday, 6 January 2012

Creating PDF and attached with email in iphone | Objective C



I'm making an application which requires following requirements.
Steps:

1) Capturing a photo from iPhone Camera.
2) Creating PDF.
3) Saving photo in iPhone Library.
4) Email Attachment with PDF.


In .h file


#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMailComposeViewController.h>

Protocols Used 
<MFMailComposeViewControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

NSString *imagePathString;
IBOutlet UIImageView *imgView;

@property (nonatomic,retain) NSString *imagePathString;
@property (nonatomic,retain) UIImageView *imgView;

-(IBAction) scanningPrescription : (id) sender;
-(IBAction) emailToPharmacist : (id) sender;

//EMAIL_FUNCTIONS
-(void)showPicker;
-(void)displayComposerSheet ;
-(void)launchMailAppOnDevice;


In .m file
#import <QuartzCore/QuartzCore.h>

@synthesize imagePathString,imgView;

- (void)viewDidLoad {

    self.imagePathString = [[NSString alloc]init];
    [super viewDidLoad];
}
-(IBAction) capturingPhoto : (id) sender{

if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
// If camera is available

UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.delegate = self;
[self presentModalViewController:imagePicker animated:YES];

}else {
// Camera is not available

UIAlertView *alertMsg = [[UIAlertView alloc] initWithTitle:nil message:@"Functionality is only available on devices with cameras." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertMsg show];
[alertMsg release];


}


}

/*----------------------------DELEGATES_METHOD_FOR_CAMERA-----------------------*/

//CANCEL_CAPTURING
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {

    [self dismissModalViewControllerAnimated:YES];
}

//FINISH_CAPTURING_AN_IMAGE

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

NSLog(@"INFO_DESCRIPTion %@",[info description]);

UIImage * image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

// You have the image. You can use this to present the image in the next view like you require in #3.
//  Access the uncropped image from info dictionary

// SAVE_IMAGE
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);

[picker release];
[self dismissModalViewControllerAnimated:YES];

}

//SAVE_IMAGE

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{

// Unable to save the image
if (error){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
  message:@"Unable to save image to Photo Album."
 delegate:self cancelButtonTitle:@"Ok"
otherButtonTitles:nil];

[alert show];
[alert release];

}
else{
// All is well

//Take an ImageView and set capturing image on that.
self.imgView.image=image;


 
    //create the file path to store our PDF document (will be created inside our app's documents directory)
    //If you're using the simulator, the file can be found in: homeFolder/Library/Application Support/iPhone Simulator/versionOfIOS_Simulator/Applications/SomeWeirdStringIdentifyingYourApp/Documents/
 
    NSString *fileName = @"YOUR_PDF_NAME.pdf";
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *saveDirectory = [paths objectAtIndex:0];
NSString *saveFileName = fileName;
//This String used for Saving a Path on which capturing image to be stored.
self.imagePathString = [saveDirectory stringByAppendingPathComponent:saveFileName];
    NSLog(@"%@",self.imagePathString);

}


}


-(IBAction) emailToSomeElse : (id) sender{

[self showPicker];
}

-(void)showPicker
{

Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
if (mailClass != nil)
{
// We must always check whether the current device is configured for sending emails
if ([mailClass canSendMail])
{
[self displayComposerSheet];
}
else
{
[self launchMailAppOnDevice];
}
}

}


#pragma mark -
#pragma mark Compose Mail

// Displays an email composition interface inside the application. Populates all the Mail fields.
-(void)displayComposerSheet
{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;

[picker setSubject:@"SUBJECT"];


// Set up recipients
NSArray *toRecipients = [NSArray arrayWithObject:@"TO_EMAIL_ADDRESS"];

NSArray *ccRecipients = [[NSArray alloc] init];
NSArray *bccRecipients = [[NSArray alloc] init];

[picker setToRecipients:toRecipients];
[picker setCcRecipients:ccRecipients];
[picker setBccRecipients:bccRecipients];

/*// Attach an image to the email
NSString *path = [[NSBundle mainBundle] pathForResource:@"IMAGE_NAME" ofType:@"png"];
NSData *myData = [NSData dataWithContentsOfFile:path];
[picker addAttachmentData:myData mimeType:@"image/png" fileName:@"IMAGE_NAME"];
*/

//PDF_ATTACHMENT
//Take ImageView on View and on UIGraphicsBeginPDFContextToData(passing imageview bounds i.e capturing photo on imageview) and renderInContext method using Quartz framework

NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData(pdfData,self.imgView.bounds, nil);
UIGraphicsBeginPDFPage();

[self.imgView.layer renderInContext:UIGraphicsGetCurrentContext()];

UIGraphicsEndPDFContext();



[picker addAttachmentData:pdfData mimeType:@"pdf" fileName:@"YOUR_PDF_NAME.pdf"];


// Fill out the email body text
NSString *emailBody = @"Cool!";
[picker setMessageBody:emailBody isHTML:YES];

[self presentModalViewController:picker animated:YES];
    [picker release];
}


// Dismisses the email composition interface when users tap Cancel or Send. Proceeds to update the message field with the result of the operation.
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
//Image View asssign nil after email send successsfully.
self.imgView.image=nil;
//message.hidden = NO;  // Useless

// Notifies users about errors associated with the interface
switch (result)
{
case MFMailComposeResultCancelled:{
//message.text = @"Result: cancelled";
NSString *str =@"Your mail has been cancelled.Try Again!";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Mail Cancel" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK",nil];
[alert show];
[alert release];
break;
}
case MFMailComposeResultSaved:{
//message.text = @"Result: saved";
NSString *str =@"Your Mail has been saved";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Mail Saved" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK",nil];
[alert show];
[alert release];
break;
}
case MFMailComposeResultSent:{
//message.text = @"Result: sent";
NSString *str =@"Your mail has been sent successfully.Thanks!";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Mail Sent" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK",nil];
[alert show];
[alert release];
break;
}
case MFMailComposeResultFailed:{
//message.text = @"Result: failed";
NSString *str =@"Your mail hase been failed.Try Again!";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Mail Failed" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK",nil];
[alert show];
[alert release];
break;
}
default:{
//message.text = @"Result: not sent";
NSString *str =@"Your Mail has not been sent";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Mail Not Sent" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK",nil];
[alert show];
[alert release];
break;
}
}
[self dismissModalViewControllerAnimated:YES];
}


#pragma mark -
#pragma mark Workaround

// Launches the Mail application on the device.
-(void)launchMailAppOnDevice
{
NSString *recipients = @"mailto:&subject=";

// FOR TESTING
//NSString *recipients = @"mailto:@""&subject=";
NSString *body = @"&body=";

NSString *email1 = [NSString stringWithFormat:@"%@%@", recipients, body];
email1 = [email1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email1]];
}

Wednesday, 14 December 2011

Touch/Tap Event on single Object in iPhone | Populate Custom MenuItems


#pragma mark TouchEvents
-(void) touchesBegan : (NSSet *)touches withEvent : (UIEvent *)event {

UITouch *touch = [[event allTouches]anyObject];

CGPoint touchLocation = [touch locationInView:self.view];
CGPoint origin = self.yourImgView.frame.origin;
CGFloat x2 = origin.x + self.yourImgView.frame.size.width;
CGFloat y2 = origin.y + self.yourImgView.frame.size.height;

/**
Touch Event only responds on Your ImageView
*/

if ((touchLocation.x >= origin.x && touchLocation.x <= x2) && (touchLocation.y >= origin.y && touchLocation.y <= y2))
    {

if ([touch tapCount] == 2) {

[self becomeFirstResponder];

/** Description
 * Create Custom UIMenu Item
 * If we want more Menuitems.So, we can take an array and selector on each items
 * setTargetRect : On which frame you want to tap and display menu item on it.
 * setMenuVisible: No Menu items to hide.
 * menuRect : Where you want to display menu items.
 */

UIMenuItem *menuPasteItem = [[UIMenuItem alloc] initWithTitle:@"Paste" action:@selector(YourMethodName1)];
UIMenuItem *menuCopyItem = [[UIMenuItem alloc] initWithTitle:@"Copy" action:@selector(YourMethodName2)];

UIMenuController *menuController = [UIMenuController sharedMenuController];

CGRect menuRect = CGRectMake(0,10,150,100);

[menuController setTargetRect:menuRect inView:self.yourImgView];
menuController.menuItems=[NSArray arrayWithObjects:menuPasteItem,menuCopyItem,nil];
[menuController setMenuVisible:YES animated:YES];

}


    }

}

#pragma mark BOOL operations

-(BOOL) canBecomeFirstResponder{

return YES;
}

-(BOOL) canPerformAction:(SEL)action withSender:(id)sender{

BOOL confirm = NO;

if (action == @selector(YourMethodName1))
confirm = YES;
if (action == @selector(YourMethodName2))
confirm = YES;

return confirm;

}


I love to write this post, it really helps for me.

Hope

Thursday, 8 December 2011

WCF service call from iPhone

POST_PARAMETERS_IN_WCF_BASED_SERVICE

1) CODE_IN_.NET

METHOD_SIGNATURE

[OperationContract]
[WebInvoke( Method="POST",

RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)
]



2) CODE_IN_OBJECTIVEC

TERMS_USED

kDevBaseURI="YOUR_REQUEST_PATH_URL"

-(NSString *) postRequest : (NSString *)requestMethod andRequestData : (NSMutableDictionary *) requestData{

NSString *requestString = [[NSString alloc] initWithFormat:@"%@/%@",kDevBaseURI,requestMethod];

NSLog(@"Request:%@",requestString);

NSURL *url=[NSURL URLWithString:requestString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

//IN_CASE_BACKEND_ACCEPTS_AS
//_REQUESTFORMAT_IS_JSON_FORMAT

NSString *postString = [NSString stringWithFormat:@"{\"name\":\"%@\",\"email\":\"%@\",\"password\":\"%@\"}",@"YOUR_NAME",@"YOUR_EMAIL_ID",@"YOUR_PASSWORD"];

//OTHERWISE
//NO_REQUEST_FORMAT

NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init];

[jsonDict setObject:@"YOUR_NAME" forKey:@"name"];

[jsonDict setObject:@"YOUR_EMAIL_ID" forKey:@"email"];

[jsonDict setObject:@"YOUR_PASSWORD" forKey:@"password"];

NSString *postString = [requestData JSONRepresentation];
NSLog(@"POST_STRING:%@",postString);

//

NSData *postBody = [postString dataUsingEncoding:NSUTF8StringEncoding];
NSString *contentType = @"application/json; charset=utf-8";
[request addValue:contentType forHTTPHeaderField:@"Content-Type"];

unsigned long long postLength = postBody.length;

NSString *contentLength = [NSString stringWithFormat:@"%llu",postLength];
[request addValue:contentLength forHTTPHeaderField:@"Content-Length"];

[request setHTTPMethod:@"POST"];
[request setHTTPBody:postBody];


NSError *error;
NSURLResponse *response;
NSData *webresponse = [[NSData data] retain];

webresponse = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *strJSON = [[NSString alloc]initWithBytes: [webresponse bytes]
length:[webresponse length] encoding:NSUTF8StringEncoding];


NSLog(@" here is web data : %@",strJSON);

return strJSON;

}


GET_PARAMETERS_IN_WCF_BASED

-(void) getRequest {

   NSString *requestString = [[NSString alloc] initWithFormat:@"%@/check?a=%@",kDevBaseURI,@"ABC"];
NSLog(@"Request check :%@",requestString);

NSString *responseString = [self stringWithUrl:[NSURL URLWithString:requestString]];
NSLog(@"Response :%@",responseString);

}

THIS_GENERIC_FUNCTION_USED_IN_BOTH_REQUEST(POST || GET)

- (NSString *)stringWithUrl:(NSURL *)url
{
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
    // Fetch the JSON response
NSData *urlData;
NSURLResponse *response;
NSError *error;
    NSString *result;
 
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
                                    returningResponse:&response
                                                error:&error];
 
  // Construct a String around the Data from the response
result = [[[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding] autorelease];
 
    //NSLog(@"stringWithUrl urlRequest: %@ result: %@ response: %@ error: %@",urlRequest,result,response,error);
 
    return result;
}