AVAssetWriter is always on AVAssetWriterStatusFailed status - ios7

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.

Related

MKMapView pin animation and annotation

I'm using the google places API to find some restaurants nearby (based on current location using core location manager); currently, I'm able to drop pins. I use the searchBarSearchButtonClicked method, and inside of a dispatch_async block, I call my method to parse through my serialized data and attribute values to properties of my pin class (class MKAnnotation). I'd like to animate my pin drops, and also actually display annotations...for some reason I had them working before but now they won't show up when I click on the pins.
VIEW CONTROLLER.H
#interface MyViewController : UIViewController <CLLocationManagerDelegate, MKMapViewDelegate, UISearchBarDelegate,NSURLSessionDelegate> {
CLLocationManager *locationManager;
}
#property (strong, nonatomic) MKMapView *mapView;
#property (strong, nonatomic) UISearchBar *searchBar;
#property (strong, nonatomic) UIImageView *logo;
#property (strong, nonatomic) UIToolbar *toolBar;
#property (strong, nonatomic) NSString *places;
#end
VIEW CONTROLLER.M
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
NSLog(#"%#", self.searchBar.text);
NSURLSession *session = [NSURLSession sharedSession];
NSString *s = [NSString
stringWithFormat:#"https://maps.googleapis.com/maps/api/place/nearbysearch/json?keyword=%#&location=%f,%f&radius=5&types=food&key=AIzaSyCg6Ahz_hQ1f2rjKEAWcJKQetblPVjHS-E", self.searchBar.text, locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude];
NSURL *url = [[NSURL alloc]initWithString:s];
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
NSData *dataResponse = [[NSData alloc]initWithContentsOfURL:location];
NSDictionary *dictionaryReponse = [NSJSONSerialization JSONObjectWithData:dataResponse options:kNilOptions error:&error];
NSMutableArray *finalResults = [dictionaryReponse objectForKey:#"results"];
dispatch_async(dispatch_get_main_queue(), ^{
[self placeAnnotations:finalResults];
});
}];
[task resume];
}
-(void)placeAnnotations:(NSMutableArray *)data {
for (id<MKAnnotation> annotation in self.mapView.annotations) {
// if ([annotation isKindOfClass:[MapPoint class]]) {
[self.mapView removeAnnotation:annotation];
// }
}
for (int i = 0; i < [data count]; i++) {
NSDictionary *place = [data objectAtIndex:i];
NSDictionary *geo = [place objectForKey:#"geometry"];
NSDictionary *location = [geo objectForKey:#"location"];
NSString *name = [place objectForKey:#"name"];
NSString *vicinity = [place objectForKey:#"vicinity"];
CLLocationCoordinate2D placeCoord;
placeCoord.latitude = [[location objectForKey:#"lat"] doubleValue];
placeCoord.longitude = [[location objectForKey:#"lng"] doubleValue];
MapPoint *newPin = [MapPoint new];
newPin.name = name;
newPin.address = vicinity;
newPin.coordinate = placeCoord;
MKPinAnnotationView *newAnnotation = [[MKPinAnnotationView alloc]initWithAnnotation:newPin reuseIdentifier:#"annotation"];
newAnnotation.animatesDrop = YES;
[self.mapView addAnnotation:newPin];
}
[self.mapView reloadInputViews];
}
I

How to add directions among two custom locations in Mapview for IOS 7 (objective c)

I have to add directions among two custom locations in IOS 7.
Any one tell me please.
Thanks.
Try this:
1.Create a file named ViewController with MKMapView as an IBOutlet and connect the map view from Storyboard to MKMapView property.
[ViewController.h]
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <MapKit/MKAnnotation.h>
#interface ViewController : UIViewController <MKMapViewDelegate>
#property (nonatomic, strong) IBOutlet MKMapView *mapView;
#end
[ViewController.m]
#import "ViewController.h"
#import "Annotation.h"
#define Location1Latitude -12.429481
#define Location1Longitude 130.863324
#define Location2Latitude -32.15037
#define Location2Longitude 115.782909
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.mapView.delegate = self;
[self.mapView setMapType:MKMapTypeStandard];
[self.mapView setZoomEnabled:YES];
[self.mapView setScrollEnabled:YES];
//Annotation
NSMutableArray * locations = [[NSMutableArray alloc] init];
CLLocationCoordinate2D location;
Annotation * myAnn;
// Location 1 Annotation
myAnn = [[Annotation alloc] init];
location.latitude = Location1Latitude;
location.longitude = Location1Longitude;
[locations addObject:myAnn];
//Location 2 Annotation
myAnn = [[Annotation alloc] init];
location.latitude = Location2Latitude;
location.longitude = Location2Longitude;
myAnn.coordinate = location;
[locations addObject:myAnn];
[self.mapView addAnnotations:locations];
[self performSelector:#selector(drawRoute) withObject:self afterDelay:1.0];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)drawRoute {
MKPlacemark *source = [[MKPlacemark alloc]initWithCoordinate:CLLocationCoordinate2DMake(Location1Latitude, Location1Longitude) addressDictionary:nil];
MKMapItem *srcMapItem = [[MKMapItem alloc]initWithPlacemark:source];
[srcMapItem setName:#"source"];
MKPlacemark *destination = [[MKPlacemark alloc]initWithCoordinate:CLLocationCoordinate2DMake(Location2Latitude, Location2Longitude) addressDictionary:nil ];
MKMapItem *destMapItem = [[MKMapItem alloc]initWithPlacemark:destination];
[destMapItem setName:#"dest"];
MKDirectionsRequest *request = [[MKDirectionsRequest alloc]init];
[request setSource:srcMapItem];
[request setDestination:destMapItem];
[request setTransportType:MKDirectionsTransportTypeAutomobile];
MKDirections *direction = [[MKDirections alloc]initWithRequest:request];
[direction calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
NSLog(#"response = %# \n eror %#",response, error);
NSArray *arrRoutes = [response routes];
[arrRoutes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
MKRoute *rout = obj;
MKPolyline *line = [rout polyline];
[self.mapView addOverlay:line];
NSLog(#"Rout Name : %#",rout.name);
NSLog(#"Total Distance (in Meters) :%f",rout.distance);
NSArray *steps = [rout steps];
NSLog(#"Total Steps : %lu",(unsigned long)[steps count]);
[steps enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(#"Rout Distance : %f",[obj distance]);
NSLog(#"Rout Instruction : %#",[obj instructions]);
}];
}];
}];
}
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id < MKOverlay >)overlay
{
MKPolylineRenderer *renderer = [[MKPolylineRenderer alloc] initWithOverlay:overlay];
renderer.strokeColor = [UIColor colorWithRed:55.0/255.0 green:160.0/255.0 blue:250.0/255.0 alpha:1.0];
renderer.lineWidth = 4.0;
return renderer;
}
2.Create a file named Annotation.
[Annotation.h]
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#interface Annotation : NSObject <MKAnnotation>
#property(nonatomic, assign) CLLocationCoordinate2D coordinate;
#property(nonatomic, copy) NSString * title;
#property(nonatomic, copy) NSString * subtitle;
#property(nonatomic, copy) NSString * imageName;
#end
[Annotation.m]
#import "Annotation.h"
#implementation Annotation
#end

Login to web services

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];

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{
}