Login to web services - objective-c

I am currently stuck on the part where user use his username and password to view his data. I did try every piece of information on this website to find out how to make it work with no luck so far if anyone can point me in the right direction I'll be grateful.
here is my .h file:
#import <UIKit/UIKit.h>
#interface ePaymentLoginViewController : UIViewController {
IBOutlet UITextField *__weak usernameField;
IBOutlet UITextField *__weak passwordField;
IBOutlet UIButton *__weak loginButton;
IBOutlet UIActivityIndicatorView *__weak loginIndicator;
}
#property (weak, nonatomic) UITextField *usernameField;
#property (weak, nonatomic) UITextField *passwordField;
#property (weak, nonatomic) UIButton *loginButton;
#property (weak, nonatomic) UIActivityIndicatorView *loginIndicator;
- (IBAction) login: (id) sender;
- (IBAction)backButton:(id)sender;
- (IBAction)cancelButton:(id)sender;
#end
here is my .m file:
#import "ePaymentLoginViewController.h"
#interface ePaymentLoginViewController ()
#end
#implementation ePaymentLoginViewController
#synthesize usernameField;
#synthesize passwordField;
#synthesize loginButton;
#synthesize loginIndicator;
- (IBAction) login: (id) sender
{
NSString *post =[NSString stringWithFormat:#"%#/%#",usernameField.text, passwordField.text];
NSString *hostStr = #"http://ourserver/mobilepay/MobilePayService.svc/verify/%#/%#";
hostStr = [hostStr stringByAppendingString:post];
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
if([serverOutput isEqualToString:#"text/json"]){
UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:#"Congrats" message:#"You are authorized" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alertsuccess show];
} else {
UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:#"Login Failed" message:#"Username or Password Incorrect" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alertsuccess show];
loginIndicator.hidden = TRUE;
loginButton.enabled = TRUE;
[loginIndicator startAnimating];
}
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn’t have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren’t in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
-(IBAction)backButton:(id)sender{
[self dismissViewControllerAnimated:YES completion:nil];
}
-(IBAction)cancelButton:(id)sender{
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
after successful login this is how the url should look and it will send JSON data
http://ourserver/mobilepay/MobilePayService.svc/verify/user123/test123
{
"Table": [
{
"comp_filenum": 1006842,
"comp_namar": "username123",
"comp_civid": "100000"
}
],
"Table1": [
{
"tran_num": 30301,
"inst_val": 1725,
"balance": 3450,
"late_amount": 3450,
"late_inst_no": 2,
"legal_status": 0,
"baloon_balance": 0,
"late_bal_no": 0,
"remain_bal_no": 0,
"clienttype": 2,
"filenumber": 1006842,
"customername": "username123",
"civilid": "100000",
"saleprice": 82800,
"costprice": 66005,
"last_receiptnumber": "e22512",
"last_paydate": "2012-05-02T00:00:00",
"last_payamount": 1725,
"paidamount": 79350,
"remaininginstallment": 16
},
So what am i doing wrong at this point and what is the right way to do it.

Try with below line :
NSString *hostStr = [NSString stringWithFormat:#"http://ourserver/mobilepay/MobilePayService.svc/verify/%#/%#",usernameField.text, passwordField.text];
NSURL *aURL = [NSURL URLWithString: hostStr];
NSLog(#"%#",aURL); // check the log
NSData *dataURL = [NSData dataWithContentsOfURL:aURL];

Try to show the value of hostStr
NSString *post =[NSString stringWithFormat:#"%#/%#",usernameField.text, passwordField.text];
NSString *hostStr = #"http://ourserver/mobilepay/MobilePayService.svc/verify/%#/%#";
hostStr = [hostStr stringByAppendingString:post];
It will show :
http://ourserver/mobilepay/MobilePayService.svc/verify/%#/%#username/password
Try with this :
NSString *hostStr = #"http://ourserver/mobilepay/MobilePayService.svc/verify/%#/%#";
NSString *url = [NSString stringWithFormat:hostStr,usernameField.text, passwordField.text];

Related

AVAssetWriter is always on AVAssetWriterStatusFailed status

my goal is to apply some filters on the camera input in real time. To do that step by step, I'm trying to get the input form the camera with AVFoundation record a video and save it in the camera roll. I tried, but for some reason the AVAssetWriter is always in AVAssetWriterStatusFailed and so the appendSampleBuffer: method always failed. Where is my error? Someone can help me?
Thanks!
ViewController.h
#import <UIKit/UIKit.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <AVFoundation/AVFoundation.h>
#interface ViewController : UIViewController <AVCaptureVideoDataOutputSampleBufferDelegate>
#property (weak, nonatomic) IBOutlet UIImageView *imageView;
#property (weak, nonatomic) IBOutlet UIButton *startRecButton;
#property (weak, nonatomic) IBOutlet UIButton *stopRecButton;
#property (weak, nonatomic) IBOutlet UIButton *startVideocamera;
- (IBAction)startRecordingButtonPressed:(UIButton *)sender;
- (IBAction)stopRecordingButtonPressed:(UIButton *)sender;
- (IBAction)startVideocameraButtonPressed:(UIButton *)sender;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#property (strong, nonatomic) AVAssetWriter* videoAssetWriter;
#property (strong, nonatomic) AVAssetWriterInput* videoAssetWriterInput;
#property (strong, nonatomic) NSURL* temporaryVideoURL;
#end
#implementation ViewController
#pragma mark - Variables
#synthesize imageView;
#synthesize videoAssetWriter;
#synthesize videoAssetWriterInput;
#synthesize temporaryVideoURL;
//initCaptureSession Method
AVCaptureSession* captureSession;
AVCaptureDevice* videoCaptureDevice;
AVCaptureDeviceInput* videoCaptureDeviceInput;
AVCaptureVideoDataOutput* videoDataOutput;
dispatch_queue_t videoQueue;
//captureOutput:didOutputSampleBuffer Method
CMSampleBufferRef currentSampleBuffer;
BOOL isRecording;
//newPixelBufferFromCGImage Method
CGAffineTransform frameTransform;
CGSize frameSize;
#pragma mark - User Interface
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)startRecordingButtonPressed:(UIButton *)sender {
[self initWriter];
}
- (IBAction)stopRecordingButtonPressed:(UIButton *)sender {
[self stopWriter];
}
- (IBAction)startVideocameraButtonPressed:(UIButton *)sender {
[self initCaptureSession];
}
#pragma mark - Capture Utils
-(void) initCaptureSession{
captureSession = [[AVCaptureSession alloc] init];
[captureSession setSessionPreset:AVCaptureSessionPreset1280x720];
videoCaptureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError* error;
videoCaptureDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:videoCaptureDevice error:&error];
if([captureSession canAddInput:videoCaptureDeviceInput]){
[captureSession addInput:videoCaptureDeviceInput];
}
videoDataOutput = [[AVCaptureVideoDataOutput alloc]init];
[captureSession addOutput:videoDataOutput];
videoQueue = dispatch_queue_create("videoQueue", NULL);
[videoDataOutput setAlwaysDiscardsLateVideoFrames:NO];
[videoDataOutput setSampleBufferDelegate:self queue:videoQueue];
NSString* key = (NSString*)kCVPixelBufferPixelFormatTypeKey;
NSNumber* value = [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA];
NSDictionary* videoSettings = [NSDictionary dictionaryWithObject:value forKey:key];
[videoDataOutput setVideoSettings:videoSettings];
[captureSession startRunning];
}
-(void) captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer: (CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection{
currentSampleBuffer = sampleBuffer;
CGImageRef image = [self imageFromSampleBuffer:currentSampleBuffer];
dispatch_sync(dispatch_get_main_queue(),
^{
if(!isRecording){
imageView.image = [UIImage imageWithCGImage: image scale:1.0 orientation:UIImageOrientationRight];
}
else{
imageView.image = [UIImage imageWithCGImage: image scale:1.0 orientation:UIImageOrientationRight];
// [videoAssetWriterInput appendSampleBuffer:currentSampleBuffer];
if (![videoAssetWriterInput appendSampleBuffer:sampleBuffer]) {
[self showError:[videoAssetWriter error]];
}
NSLog(#"%ld", (long)[videoAssetWriter status]);
}
});
CGImageRelease(image);
}
-(void)captureOutput:(AVCaptureOutput *)captureOutput didDropSampleBuffer: (CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection{
NSLog(#"didDropSampleBuffer CALLED");
}
#pragma mark - Writer Utils
-(void) initWriter{
temporaryVideoURL = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#%#", NSTemporaryDirectory(), #"Movie.MOV"]];
NSLog(#"%#", temporaryVideoURL);
NSError* error;
videoAssetWriter = [[AVAssetWriter alloc] initWithURL:temporaryVideoURL fileType:AVFileTypeQuickTimeMovie error:&error];
NSParameterAssert(videoAssetWriter);
NSLog(#"%ld", (long)[videoAssetWriter status]);
NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
AVVideoCodecH264, AVVideoCodecKey,
[NSNumber numberWithInt:1280], AVVideoWidthKey,
[NSNumber numberWithInt:720], AVVideoHeightKey,
nil];
videoAssetWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings];
NSParameterAssert(videoAssetWriterInput);
NSLog(#"%ld", (long)[videoAssetWriter status]);
if([videoAssetWriter canAddInput:videoAssetWriterInput]){
[videoAssetWriter addInput:videoAssetWriterInput];
}
isRecording = YES;
[videoAssetWriter startWriting];
NSLog(#"%ld", (long)[videoAssetWriter status]);
}
-(void) stopWriter{
[videoAssetWriterInput markAsFinished];
[videoAssetWriter finishWritingWithCompletionHandler:^{
NSLog(#"finishWritingWithCompletionHandler CALLED");
isRecording = NO;
[self saveVideoToCameraRoll];
videoAssetWriter =nil;
videoAssetWriterInput= nil;
}];
// [videoAssetWriter finishWriting];
// isRecording = NO;
// [self saveVideoToCameraRoll];
}
-(void) saveVideoToCameraRoll{
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeVideoAtPathToSavedPhotosAlbum:temporaryVideoURL completionBlock:^(NSURL *assetURL, NSError *error){
NSLog(#"ASSET URL: %#", [assetURL path]);
if(error) {
NSLog(#"CameraViewController: Error on saving movie : %# {imagePickerController}", error);
}
else {
NSLog(#"Video salvato correttamente in URL: %#", assetURL);
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:[temporaryVideoURL path]];
NSLog(#"IL FILE ESISTE: %hhd", fileExists);
NSLog(#"E PESA: %#", [[[NSFileManager defaultManager] attributesOfItemAtPath: [temporaryVideoURL path] error:&error] objectForKey:NSFileSize]);
}
}];
}
This error is because of a reason that a file with similar filename already exist.
In my case, I was using a static file name for testing purpose, which caused the error. Making it something unique something like:
"\(Date().timeIntervalSince1970).mp4" fixed it.

iOS UITableView Only Reloads Cell Data When Scrolling

I am working on my first Objective-C app for iOS and am having an issue with reloading the data in a UITableView.
After reloading the data the cell content will only update when the cell is scrolled above of below the viewable area of the container.
Here is my .h code:
#import <UIKit/UIKit.h>
#import "AFHTTPClient.h"
#import "AFJSONRequestOperation.h"
#interface HelloWorldViewController : UIViewController <UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource>{
NSMutableArray *tableViewArray;
IBOutlet UITableView *tableView;
}
#property (nonatomic, retain) NSMutableArray *tableViewArray;
#property (weak, nonatomic) IBOutlet UILabel *connectionLabel;
#property (nonatomic, retain) IBOutlet UITableView *tableView;
#property (weak, nonatomic) IBOutlet UITextView *textArea;
#property (weak, nonatomic) IBOutlet UITextField *textField2;
#property (weak, nonatomic) IBOutlet UILabel *label;
#property (weak, nonatomic) IBOutlet UITextField *textField;
#property (copy, nonatomic) NSString *userName;
#property (copy, nonatomic) NSString *passWord;
#property (copy, nonatomic) NSMutableString *serverResponse;
- (IBAction)callHome:(id)sender;
#end
and .m code:
#import "HelloWorldViewController.h"
#interface HelloWorldViewController ()
#end
#implementation HelloWorldViewController
#synthesize tableViewArray;
#synthesize connectionLabel;
#synthesize userName = _userName;
#synthesize passWord = _password;
#synthesize serverResponse = _serverResponse;
#synthesize tableView;
#synthesize textArea;
#synthesize textField2;
#synthesize label;
#synthesize textField;
- (void)viewDidLoad
{
[super viewDidLoad];
tableViewArray = [[NSMutableArray alloc] init];
[tableViewArray addObject:#"TEST1"];
[tableViewArray addObject:#"TEST2"];
[tableViewArray addObject:#"TEST3"];
}
- (void)viewDidUnload
{
[self setTextField:nil];
[self setLabel:nil];
[self setTextField2:nil];
[self setTextArea:nil];
[self setTableView:nil];
[self setConnectionLabel:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
if (theTextField == self.textField) {
[theTextField resignFirstResponder];
}
return YES;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [tableViewArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.textLabel.text = [self.tableViewArray objectAtIndex: [indexPath row]];
return cell;
}
- (IBAction)callHome:(id)sender {
self.userName = self.textField.text;
self.passWord = self.textField2.text;
NSMutableString *tempResponse = [[NSMutableString alloc] initWithFormat:#""];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"http://example.com/"]];
[client setAuthorizationHeaderWithUsername:self.userName password:self.passWord];
[client getPath:#"login.do" parameters:nil
success:^( AFHTTPRequestOperation *operation , id responseObject ){
NSLog(#"Authentication Success: %d", operation.response.statusCode);
self.serverResponse = [NSMutableString stringWithFormat:#"Authentication Success: %d", operation.response.statusCode ];
[tempResponse appendString: self.serverResponse];
self.textArea.text = tempResponse;
}
failure:^(AFHTTPRequestOperation *operation , NSError *error){
NSLog(#"Authentication Error: %#\n%#", error, operation);
}
];
[client getPath:#"test.json.do" parameters:nil
success:^( AFHTTPRequestOperation *operation , id responseObject ){
NSLog(#"Retrieval Success: %d", operation.response.statusCode);
NSDictionary *results = [operation.responseString JSONValue];
NSMutableArray *buildings = [results objectForKey:#"buildings"];
NSMutableArray *names = [[NSMutableArray alloc] init];
for (NSDictionary *building in buildings)
{
[names addObject:[building objectForKey:#"name"]];
}
self.tableViewArray = names;
self.serverResponse = [NSMutableString stringWithFormat:#"\nBuilding List Retrieval Success: %d", operation.response.statusCode ];
[tempResponse appendString: self.serverResponse];
self.connectionLabel.text = tempResponse;
}
failure:^(AFHTTPRequestOperation *operation , NSError *error){
NSLog(#"Retrieval Error: %#\n%#", error, operation);
}
];
NSLog(#"tableView is: %#", [tableView description]);
[tableView reloadData];
}
#end
When I call [self.tableView description]the result is null, but if I call it from cellForRowAtIndexPath then I get the following result:
tableView is: <UITableView: 0x8a71000; frame = (0 0; 280 191); clipsToBounds = YES; autoresize = W+H; layer = <CALayer: 0x6b7e860>; contentOffset: {0, 0}>. Delegate: HelloWorldViewController, DataSource: HelloWorldViewController
Here's a screenshot of interface builder:
All help is appreciated! Thanks!
You're probably not connecting the UITableView in the interface builder..
You have to drag while pressing ctrl from the file's owner to the UITableView and connect it.
Also, you should not access your properties without self, you should do:
#synthesize tableViewArray = _tableViewArray;
and then access it with:
self.tableViewArray
try to avoid accessing your ivars directly, use the property!
Good luck!
It looks like you may have not hooked up your UITableView with the HelloWorldViewController tabelView property in IB.

App crashed when trying to change UITextView.text

My app crashed when i trying to change UITextView text.
Here is the code: (header file):
//
#import <UIKit/UIKit.h>
#interface DetailViewController : UIViewController {
IBOutlet UIImageView *appImage;
IBOutlet UILabel *appName;
IBOutlet UILabel *appDeveloper;
IBOutlet UILabel *appVersion;
UIActivityIndicatorView *loading;
IBOutlet UITextView *appAbout;
NSString *selectedApp;
}
#property (nonatomic, retain) NSString *selectedApp;
#property (nonatomic, retain) IBOutlet UIImageView *appImage;
#property (nonatomic, retain) IBOutlet UILabel *appName;
#property (nonatomic, retain) IBOutlet UILabel *appDeveloper;
#property (nonatomic, retain) IBOutlet UILabel *appVersion;
#property (nonatomic, retain) UIActivityIndicatorView *loading;
#property (nonatomic, retain) UITextView *appAbout;
#end
implementation file:
- (void)loadData {
NSString *trimmedString = [selectedApp stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
self.navigationItem.title = #"Info";
NSLog(#"%#", trimmedString);
NSString *website = [NSString stringWithFormat:#"http://shaymargolisapps.x10.mx/send.php?mission=GetNameOfApps&aname=%#", trimmedString];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:website]];
NSString *strResult = [[[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding]autorelease];
appName.text = strResult;
NSString *website1 = [NSString stringWithFormat:#"http://shaymargolisapps.x10.mx/send.php?mission=GetDeveloperOfApp&aname=%#", trimmedString];
NSData *dataURL1 = [NSData dataWithContentsOfURL:[NSURL URLWithString:website1]];
NSString *strResult1 = [[[NSString alloc] initWithData:dataURL1 encoding:NSUTF8StringEncoding]autorelease];
appDeveloper.text = strResult1;
NSString *website2 = [NSString stringWithFormat:#"http://shaymargolisapps.x10.mx/send.php?mission=GetVersionOfApp&aname=%#", trimmedString];
NSData *dataURL2 = [NSData dataWithContentsOfURL:[NSURL URLWithString:website2]];
NSString *strResult2 = [[[NSString alloc] initWithData:dataURL2 encoding:NSUTF8StringEncoding]autorelease];
appVersion.text = strResult2;
NSString *website3 = [NSString stringWithFormat:#"http://shaymargolisapps.x10.mx/send.php?mission=GetInfoOfApp&aname=%#", trimmedString];
NSData *dataURL3 = [NSData dataWithContentsOfURL:[NSURL URLWithString:website3]];
NSString *strResult3 = [[[NSString alloc] initWithData:dataURL3 encoding:NSUTF8StringEncoding]autorelease];
NSLog(#"%#", strResult3);
**appAbout.text = strResult3;**
NSString *website4 = [NSString stringWithFormat:#"http://shaymargolisapps.x10.mx/send.php?mission=GetImageOfApp&aname=%#", trimmedString];
NSData *dataURL4 = [NSData dataWithContentsOfURL:[NSURL URLWithString:website4]];
NSString *strResult4 = [[[NSString alloc] initWithData:dataURL4 encoding:NSUTF8StringEncoding]autorelease];
NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:strResult4]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
[appImage setImage:image];
[image release];
[imageData release];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[loading stopAnimating];
[loading setHidden:YES];
[appName setHidden:NO];
[appDeveloper setHidden:NO];
[appVersion setHidden:NO];
[appImage setHidden:NO];
[appAbout setHidden:NO];
}
My app crashed on appAbout.text = strResult3; line. What am I doing wrong?
loadData is called with [self performSelectorInBackground:#selector(loadData) withObject:nil]; from viewDidLoad
(Xcode 4.4 DP2, iPhone Simulator 5.1, base SDK 4.3)
You must not change UI* objects from a background thread. That has to be done from the main thread.
You could use gcd to perform the changes on the main thread. Something like this:
/* ... */
NSString *strResult4 = [[[NSString alloc] initWithData:dataURL4 encoding:NSUTF8StringEncoding]autorelease];
NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:strResult4]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
dispatch_async(dispatch_get_main_queue(), ^{
self.navigationItem.title = #"Info";
appName.text = strResult;
appDeveloper.text = strResult1;
appVersion.text = strResult2;
appAbout.text = strResult3;
[appImage setImage:image];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[loading stopAnimating];
[loading setHidden:YES];
[appName setHidden:NO];
[appDeveloper setHidden:NO];
[appVersion setHidden:NO];
[appImage setHidden:NO];
[appAbout setHidden:NO];
});
[image release];
[imageData release];

How to store the values which are entered in different text fields to the Server in objective C

How to store the values which are entered in different text fields to the Server in objective C, In my project i have created the a form where it consists of different text fields where the user has to enter the values to the text field, i have kept one SAVE button, where after entering the values to the text field the user has to click the Save button.
I have to save the values entered in the text fields to the server on the click of the SAVE Button.
So how to save the data or values to the server on the click of the SAVE button.
The Following is the code i have used to create the form,
In .h File :
#import <UIKit/UIKit.h>
#import "PickerViewController.h"
#interface PopAppViewController : UIViewController < NumberPickedDelegate>{
UIPopoverController *popOverController;
UIPopoverController *popOverControllerWithPicker;
PickerViewController *pickerViewController;
IBOutlet UITextField *txtTest;
IBOutlet UITextField *txtSun;
IBOutlet UITextField *txtMon;
IBOutlet UITextField *txtTue;
IBOutlet UITextField *txtWed;
IBOutlet UITextField *txtThurs;
IBOutlet UITextField *txtFri;
IBOutlet UITextField *txtSat;
IBOutlet UITextField *txtTotal;
IBOutlet UITextField *txtTask;
IBOutlet UITextField *txtProject;
}
#property (nonatomic, retain) UIPopoverController *popOverController;
#property (nonatomic, retain) UIPopoverController *popOverControllerWithPicker;
#property (nonatomic, retain) PickerViewController *pickerViewController;
#property (nonatomic, retain) UITextField *txtTest;
#property (nonatomic, retain) UITextField *txtSun;
#property (nonatomic, retain) UITextField *txtMon;
#property (nonatomic, retain) UITextField *txtTue;
#property (nonatomic, retain) UITextField *txtWed;
#property (nonatomic, retain) UITextField *txtThurs;
#property (nonatomic, retain) UITextField *txtFri;
#property (nonatomic, retain) UITextField *txtSat;
#property (nonatomic, retain) UITextField *txtTotal;
#property (nonatomic, retain) UITextField *txtTask;
#property (nonatomic, retain) UITextField *txtProject;
-(IBAction)displayPickerPopover;
-(IBAction)exit;
-(IBAction)reset;
-(IBAction)save;
-(IBAction)total;
#end
In .m file :
#import "PopAppViewController.h"
//#import "TimeSheetDatabase.h"
#implementation PopAppViewController
#synthesize popOverController,popOverControllerWithPicker,pickerViewController,txtTest,txtSun,txtMon,txtTue,txtWed,txtThurs,txtFri,txtSat,txtTotal,txtTask,txtProject;
//-(id)initWithtxtProject:(NSString *)txtProject txtTask:(NSString *)txtTask txtSun:(int)txtSun txtMon:(int)txtMon txtTue:(int)txtTue txtWed:(int)txtWed txtThurs:(int)txtThurs txtFri:(int)txtFri txtSat:(int)txtSat txtTotal:(int)txtTotal{
//
// self=[super init];
// if(self){
// self.txtProject = txtProject;
// self.txtTask = txtTask;
// self.txtSun = txtSun;
// self.txtMon = txtMon;
// self.txtTue = txtTue;
// self.txtWed = txtWed;
// self.txtThurs = txtThurs;
// self.txtFri = txtFri;
// self.txtSat = txtSat;
// self.txtTotal = txtTotal;
//
// }
//}
-(IBAction)displayPickerPopover {
[txtTest resignFirstResponder];
CGSize sizeOfPopover = CGSizeMake(300, 422);
CGPoint positionOfPopover = CGPointMake(32, 325);
[popOverControllerWithPicker presentPopoverFromRect:CGRectMake(positionOfPopover.x, positionOfPopover.y, sizeOfPopover.width, sizeOfPopover.height)
inView:self.view permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}
-(IBAction)exit{
exit(0);
}
-(IBAction)reset{
txtSun.text = #"";
txtMon.text = #"";
txtTue.text = #"";
txtWed.text = #"";
txtThurs.text = #"";
txtFri.text = #"";
txtSat.text = #"";
txtTotal.text = #"";
txtTest.text = #"";
txtTask.text = #"";
}
-(IBAction)save{
}
-(IBAction)total{
int result = [txtSun.text intValue] + [txtMon.text intValue] + [txtTue.text intValue] + [txtWed.text intValue] + [txtThurs.text intValue] + [txtFri.text intValue] + [txtSat.text intValue];
txtTotal.text = [NSString stringWithFormat:#"%d",result];
}
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
-(void)numberDidChangeTo:(NSString *)newNumber {
txtTest.text = newNumber;
}
-(void)didChangeSelection:(NSString *)newValue {
txtTest.text = newValue;
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
pickerViewController = [[PickerViewController alloc] init];
pickerViewController.delegate = self;
popOverControllerWithPicker = [[UIPopoverController alloc] initWithContentViewController:pickerViewController];
popOverController.popoverContentSize = CGSizeMake(300, 216);
// NSArray *timesheetinfo = [[TimeSheetDatabase database]getAllTimeSheet];
// for(timesheetinfo *info in timesheetinfo){
//
// NSLog(#"%# - %# ",info.project,info.task);
// }
[super viewDidLoad];
}
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[popOverController release];
[popOverControllerWithPicker release];
[pickerViewController release];
[txtTest release];
[super dealloc];
}
#end
You need to compile the data into a JSON string, and then send it to the server with an NSURLRequest
-(IBAction)save
{
// build JSON string
NSDictionary *postDictionary = [NSDictionary dictionaryWithObjectsAndKeys:self.txtTest.text, #"test",
self.txtSun.text, #"sun",
self.txtSun.text, #"mon",
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:postDictionary options:NSJSONWritingPrettyPrinted error:NULL];
// perform http request (on a background thread)
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:#"http://example.com/save.php" cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSHTTPURLResponse *urlResponse = nil;
NSError *error = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
// and now go back to the main thread
dispatch_async(dispatch_get_main_queue(), ^{
NSAutoreleasePool *mainQueuePool = [[NSAutoreleasePool alloc] init];
// debug: print response
NSLog(#"%#", [[NSString alloc] initWithData:responseData encoding:NSISOLatin1StringEncoding]);
// check for http error (this includes php exceptions)
if ([urlResponse statusCode] != 200) {
NSLog(#"save failed with status code != 200");
return;
}
[mainQueuePool release];
});
[pool release];
});
}
And in your php:
$rawData = file_get_contents("php://input");
$postData = json_decode($rawData);
print_r($postData);
As Objective-C supports pure C, you could use a C library like described here to connect to a MySQL Server.

Set Background using camera roll images

I want to know, how can I change my image app background using camera roll images. Any ideas??? How to get the camera roll paths or something like that!!!
Thanks!!!!
the following code uses a button on a toolbar, when pressed it will bring up the camera roll and then u will be able to pick the image to set
Start by adding the MobileCoreServices framework
add the following code in the .h file
#import <UIKit/UIKit.h>
#import <MobileCoreServices/MobileCoreServices.h>
#interface cameraViewController : UIViewController
<UIImagePickerControllerDelegate,
UINavigationControllerDelegate, UIPopoverControllerDelegate>
#property (nonatomic) BOOL newMedia;
#property (nonatomic, strong) IBOutlet UIImageView *imageView;
#property (nonatomic, strong) UIPopoverController *popoverController;
#property (nonatomic, strong) IBOutlet UIToolbar *toolbar;
- (IBAction)useCameraRoll: (id)sender;
#end
Add the following code in the .m file:
#synthesize imageView, popoverController, toolbar, newMedia;
- (IBAction) useCameraRoll: (id)sender
{
if ([self.popoverController isPopoverVisible]) {
[self.popoverController dismissPopoverAnimated:YES];
} else {
if ([UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypeSavedPhotosAlbum])
{
UIImagePickerController *imagePicker =
[[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType =
UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.mediaTypes = [NSArray arrayWithObjects:
(NSString *) kUTTypeImage,
nil];
imagePicker.allowsEditing = NO;
self.popoverController = [[UIPopoverController alloc]
initWithContentViewController:imagePicker];
self.popoverController.delegate = self;
[self.popoverController
presentPopoverFromBarButtonItem:sender
permittedArrowDirections:UIPopoverArrowDirectionUp
animated:YES];
newMedia = NO;
}
}
}
#pragma mark -
#pragma mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[self.popoverController dismissPopoverAnimated:true];
NSString *mediaType = [info
objectForKey:UIImagePickerControllerMediaType];
[self dismissModalViewControllerAnimated:YES];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
UIImage *image = [info
objectForKey:UIImagePickerControllerOriginalImage];
self.imageView.image = image;
if (newMedia)
UIImageWriteToSavedPhotosAlbum(image,
self,
#selector(image:finishedSavingWithError:contextInfo:),
nil);
}
else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
{
// Code here to support video if enabled
}
}
-(void)image:(UIImage *)image
finishedSavingWithError:(NSError *)error
contextInfo:(void *)contextInfo
{
if (error) {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"Save failed"
message: #"Failed to save image"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[self dismissModalViewControllerAnimated:YES];
}
Add the following in viewDidUnload:
- (void)viewDidUnload {
self.imageView = nil;
self.popoverController = nil;
self.toolbar = nil;
}
Dont forget to connect the imageview to your image and the cameraroll button to your button.
Check the docs for Assets Library.
-(void) uourCallingMethod{
UIImage *img = [UIImage imageNamed: [NSString stringWithFormat:#"image.jpg", i]];
UIImageWriteToSavedPhotosAlbum(img, nil, nil, nil);
}
(void) image:(UIImage *)image didFinishSavingWithError:(NSError *) error contextInfo:(void *) contextInfo{
}