How to save video in documents folder then upload to server [duplicate] - iphone

This question already has answers here:
How to record a video clip in ipad app and store it in documents folder
(3 answers)
Closed 9 years ago.
I am recording video from the iPad app and I want that video may be saved in documents folder or directly we may upload that to server. I have store audio file in documents but how to save a video file. I am using following code for recording video.
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
NSArray *mediaTypes = [NSArray arrayWithObject:(NSString*)kUTTypeMovie];
picker.mediaTypes = mediaTypes ;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo ;
[self presentModalViewController:picker animated:NO];
[picker release];
}
else
{
UIAlertView *alt=[[UIAlertView alloc]initWithTitle:#"Error" message:#" Camera Facility is not available with this Device" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alt show];
[alt release];
}

Try this, I've stored it with current Date-Time ::
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
[self dismissViewControllerAnimated:NO completion:nil];
NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
if ([type isEqualToString:(NSString *)kUTTypeVideo] || [type isEqualToString:(NSString *)kUTTypeMovie])
{
videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"found a video");
// Code To give Name to video and store to DocumentDirectory //
videoData = [[NSData dataWithContentsOfURL:videoURL] retain];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:#"dd-MM-yyyy||HH:mm:SS"];
NSDate *now = [[[NSDate alloc] init] autorelease];
theDate = [dateFormat stringFromDate:now];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"Default Album"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];
NSString *videopath= [[[NSString alloc] initWithString:[NSString stringWithFormat:#"%#/%#.mov",documentsDirectory,theDate]] autorelease];
BOOL success = [videoData writeToFile:videopath atomically:NO];
NSLog(#"Successs:::: %#", success ? #"YES" : #"NO");
NSLog(#"video path --> %#",videopath);
}
}
Video Uploading ::
videoData is getting from videoData = [[NSData dataWithContentsOfURL:videoURL] retain];
- (void)uploadVideo
{
NSData *imageData = videoData;
NSString *urlString=[NSString stringWithFormat:#"%s", UploadVideoService];
NSLog(#"url=== %#", urlString);
request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
/* body of the post */
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//Video Name with Date-Time
NSDateFormatter *dateFormat=[[NSDateFormatter alloc]init];
[dateFormat setDateFormat:#"yyyy-MM-dd-hh:mm:ssa"];
NSString *currDate = [dateFormat stringFromDate:[NSDate date]];
NSString *str = [NSString stringWithFormat:#"Content-Disposition: form-data; name=\"file\"; filename=\"video-%#.mov\"\r\n", currDate];
NSLog(#"String name:: %#",str);
[dateFormat release];
[body appendData:[[NSString stringWithString:str] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"result from webservice:::--> %#", returnString);
[returnString release];
}
Hope, it'll help you.
Thanks.

Once try like this,
- (void)imagePickerController:(UIImagePickerController *)imagePicker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSURL *videoUrl = (NSURL *)[info objectForKey:UIImagePickerControllerMediaURL];
NSDate *now = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"hh:mm:ss";
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
NSData *videoData = [NSData dataWithContentsOfURL:videoUrl];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedvedioPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#",[dateFormatter stringFromDate:now]]];
savedvedioPath = [savedvedioPath stringByAppendingFormat:#".mp4"];
[videoData writeToFile:savedvedioPath atomically:NO];
//here is the method to upload onto server
[self Upload_server:savedvedioPath];
[self dismissModalViewControllerAnimated:YES];
}
now define your method to upload vedio like,
-(void)Upload_server:(NSString*)file_path {
NSURL *url = [NSURL URLWithString: #"YOUR_URL_TO_UPLOAD"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setUseKeychainPersistence:YES];
[request addFile:file_path forKey:#"YOUR_KEY"];
//insted of in above line you can also use [request setData:vedioData withFileName:#"your_file_name" andContentType:#"video/mp4" forKey:#"YOUR_KEY"] by Sending vedioData of type NSData as another perameter to this method.
[request setDelegate:self];
[request setDidFinishSelector:#selector(uploadRequestFinished:)];
[request setDidFailSelector:#selector(uploadRequestFailed:)];
[request startAsynchronous];
}
now implement ASIFormDataRequest delegatemethods like,
- (void)uploadRequestFinished:(ASIHTTPRequest *)request{
NSString *responseString = [request responseString];
//do something after sucessful upload
}
- (void)uploadRequestFailed:(ASIHTTPRequest *)request{
NSLog(#" Error - Statistics file upload failed: \"%#\"",[[request error] localizedDescription]);
}
Here i took ASIFormDataRequest to upload on to server.hope it will hepls you..

//for video..
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/Mediaplayer.h>
#import <CoreMedia/CoreMedia.h>
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
NSArray *mediaTypes = [NSArray arrayWithObject:(NSString*)kUTTypeMovie];
picker.mediaTypes = mediaTypes ;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo ;
[self presentModalViewController:picker animated:NO];
[picker release];
}
else
{
UIAlertView *alt=[[UIAlertView alloc]initWithTitle:#"Error" message:#" Camera Facility is not available with this Device" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alt show];
[alt release];
}
for saving into Document folder & it also save in photo Library
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
//for video
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"video url-%#",videoURL);
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSString * videoName = [NSString stringWithFormat:#"student_%d_%d.mp4",stud_id,imgVidID];
videoPath = [documentsDirectory stringByAppendingPathComponent:videoName];
NSLog(#"video path-%#",videoPath);
[videoData writeToFile:videoPath atomically:YES];
NSString *sourcePath = [[info objectForKey:#"UIImagePickerControllerMediaURL"]relativePath];
UISaveVideoAtPathToSavedPhotosAlbum(sourcePath,nil,nil,nil);
}

Related

how to use twitter user search api in MGTwitterengine iphone

I am using MGtwitterengine in iPhone , I want to use USER search API http://api.twitter.com/1/users/search.json?q={username} but I don't find any method for this in MGTwitterengine. how can I use this API in iphone to get users.
Thanks
Use like This :-
- (void)searchforTwUser {
OAToken *access_token = [[OAToken alloc] initWithKey:[tEngine oauthKey] secret:[tEngine oauthSecret]];
OAConsumer *aconsumer = [[OAConsumer alloc] initWithKey:kOAuthConsumerKey
secret:kOAuthConsumerSecret];
OADataFetcher *fetcher = [[OADataFetcher alloc] init];
NSString *spaceString=#" ";
NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:self.searchName] invertedSet];
if ([spaceString rangeOfCharacterFromSet:set].location == NSNotFound)
{
NSString *Name = [self.searchName stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://api.twitter.com/1/users/search.json?q=%#",Name]];
NSLog(#"search name 1 is ..................................... %#",url);
OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:url
consumer:aconsumer token:access_token realm:nil
signatureProvider:nil];
[request setHTTPMethod:#"GET"];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(searchTicket:didFinishWithData:)
didFailSelector:#selector(searchTicket:didFailWithError:)];
[request release];
}
else
{
NSString *addStr = #"%20";
NSString *firstCapChar = [[searchName substringToIndex:1] capitalizedString];
NSString *cappedString = [searchName stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:firstCapChar];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://api.twitter.com/1/users/search.json?q=%#%#",cappedString,addStr]];
NSLog(#"search name 2 is ..................................... %#",url);
OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:url
consumer:aconsumer token:access_token realm:nil
signatureProvider:nil];
[request setHTTPMethod:#"GET"];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(searchTicket:didFinishWithData:)
didFailSelector:#selector(searchTicket:didFailWithError:)];
[request release];
}
[access_token release];
[aconsumer release];
}
- (void) searchTicket:(OAServiceTicket *)ticket didFinishWithData:(NSData *)data {
NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *dict = [response objectFromJSONString];
NSLog(#"Dict %#",dict);
[twSearchArray removeAllObjects];
if (twSearchArray != nil) {
[twSearchArray release];
twSearchArray = nil;
}
twSearchArray = (NSMutableArray *)dict;
NSLog(#"Twitter %#",twSearchArray);
self.twLoaded = YES;
[twSearchArray retain];
[self prepareSearchResults];
[response release];
}
- (void) searchTicket:(OAServiceTicket *)ticket didFailWithError:(NSData *)error {
NSLog(#"Errors is %#",error.description);
}

Capturing PHP Response Through NSJSONSerialization

Hi I have this code here.
NSString *name = [[NSString alloc] initWithFormat:[nameField text]];
NSString *street = [[NSString alloc] initWithFormat:[streetField text]];
NSString *city = [[NSString alloc] initWithFormat:[cityField text]];
NSString *state = [[NSString alloc] initWithFormat:[stateField text]];
NSString *zip = [[NSString alloc] initWithFormat:[zipField text]];
NSString *urlToAuthPage = [[NSString alloc] initWithFormat:#"&name=%#&street=%#&city=%#&state=%#&zip=%#&lat=%#&lon=%#", name, street, city, state, zip, str1, str2];
NSData *postData = [urlToAuthPage dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d",[urlToAuthPage length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://yourlink.com/poop.php"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
NSError *error;
NSMutableArray *infoArray = (NSMutableArray*)[NSJSONSerialization JSONObjectWithData:postData options:kNilOptions error:&error];
NSLog(#"%#", [infoArray objectAtIndex:0]);
if (conn) {
UIAlertView *successAlert = [[UIAlertView alloc] initWithTitle:#"Success!" message:#"Your party has been successfully posted" delegate:nil cancelButtonTitle:#"Close" otherButtonTitles: nil];
[successAlert show];
//NSLog(conn);
nameField.text = #"";
streetField.text = #"";
cityField.text = #"";
stateField.text = #"";
zipField.text = #"";
[nameField resignFirstResponder];
[streetField resignFirstResponder];
[cityField resignFirstResponder];
[stateField resignFirstResponder];
[zipField resignFirstResponder];
}
What I'm trying to do is get the response the server gives out that is in NSJon. I'm trying capture what is below. I've tried using an NSMutableArray to get it but it didn't work. What am I doing wrong?
{"status":1}
The problem is that NSJSONSerialization answers witha NSDictionary, not an NSMutableArray. You can't force it to be an array, since it needs a value and a key (in this case the key is "status" and the value is "1")

Prevent iCloud Backup

I make and app that the people download content and they can access it offline, it likes a catalogue. But Apple reject it because it baking up in iCloud i I'm doing the following but it seems not working.
Funciones.m
+ (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL {
const char* filePath = [[URL path] fileSystemRepresentation];
const char* attrName = "com.apple.MobileBackup";
u_int8_t attrValue = 1;
int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
return result == 0;
}
Update.m
- (void)updateImg:(NSString *)tipo {
//tomamos el ultimo update
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSTimeInterval time = [defaults doubleForKey:#"lastUpdate"];
NSLog(#"%f", time);
CatalogoAppDelegate *app = [[UIApplication sharedApplication] delegate];
NSString *post = [NSString stringWithFormat:#"lastUpdate=%f", time];
NSData *postData = [post dataUsingEncoding:NSISOLatin1StringEncoding allowLossyConversion:NO];
NSMutableURLRequest *urlRequest = [[[NSMutableURLRequest alloc] init] autorelease];
NSString *url = [NSString stringWithFormat:#"%#iPhone/update%#Img.php", app.serverUrl, tipo];
[urlRequest setURL:[NSURL URLWithString:url]];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:postData];
NSData *urlData;
NSURLResponse *response;
NSError *error;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
if(urlData) {
NSString *aStr = [[[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding]autorelease];
//NSLog(#"%#: %#", tipo, aStr);
NSArray *temp = [aStr componentsSeparatedByString:#";"];
//Direccionl Local de la APP
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
for (int i=0; i<[temp count]; i++) {
NSString *tempImg = [NSString stringWithFormat:#"%#", [temp objectAtIndex:i]];
//NSLog(#"%#", tempImg);
//pedimos cada url
NSURL *tempURL = [NSURL URLWithString:[NSString stringWithFormat:#"%#images/%#/%#", app.serverUrl, tipo, tempImg]];
//[Funciones addSkipBackupAttributeToItemAtURL:tempURL];
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:tempURL]];
NSLog(#"%#images/%#/%#", app.serverUrl, tipo, tempImg);
NSString *pngFilePath = [NSString stringWithFormat:#"%#/%#", docDir, tempImg];
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
[data1 writeToFile:pngFilePath atomically:YES];
NSURL *backUrl = [NSURL fileURLWithPath:pngFilePath];
[Funciones addSkipBackupAttributeToItemAtURL:backUrl];
}
}
[self performSelectorInBackground:#selector(finUpdate) withObject:nil];
}
Any idea what I am doing wrong?
Thanks
setxattr provides a result indicating success or an error, and Apple's addSkipBackupAttributeToItemAtURL: method checks for an error and passes this information back to your code. Your code simply ignores it. Start by determining if it's returning an error or not.
Maybe it's because your app is compatible with iOS 5.0.
Do not backup variable is only available since 5.1. Details here http://developer.apple.com/library/ios/#qa/qa1719/_index.html#//apple_ref/doc/uid/DTS40011342

NSMutableArray returns null?

I have a UITableView that gets populated my a NSMutableArray. This is how I have it set up in my .h
#interface processViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {
NSMutableArray *processList;
}
#property (copy, readwrite) NSMutableArray *processList;
and my .m
#synthesize processList;
-(void)viewDidLoad {
processList = [[NSMutableArray alloc] init];
}
I put a NSLog on it on the viewDidLoad, and it displays just fine. But after I run a action, the processList array returns null. Any ideas why?
ThanksCoulton
EDIT 1:
- (void)startUploads {
// Start UIActivity in the top
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
// Start Pool
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Display results for testing purposes (commented out)
NSArray *resultstwo = [database executeQuery:#"SELECT * FROM processes"];
for (NSDictionary *rowtwo in resultstwo) {
// Get ID
int getUserIDcount = 0;
NSArray *getUserIDInfo = [database executeQuery:#"SELECT * FROM login"];
for (NSDictionary *getUserIDRow in getUserIDInfo) {
getUserIDcount++;
NSString *oneUserID = [getUserIDRow valueForKey:#"id"];
theUserID = [NSString stringWithFormat:#"%#", oneUserID];
}
// If theUserID exists...
if (getUserIDcount == 0) {
//myTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector: #selector(checkLogin) userInfo: nil repeats: NO];
} else {
// Get URL of image
NSString *sqlImageUploadPathOne = #"./../Documents/";
NSString *sqlImageUploadPathTwo = [rowtwo valueForKey:#"image"];
NSString *getAlbumID = [rowtwo valueForKey:#"album"];
NSString *sqlImageUploadPath = [NSString stringWithFormat:#"%#%#",sqlImageUploadPathOne,sqlImageUploadPathTwo];
//testLabel.text = #"Uploading...";
// Display Image in UIImageView (uploadImageHidden)
UIImage *attemptImage = [UIImage imageNamed:sqlImageUploadPath];
[uploadImageHidden setImage:attemptImage];
// Upload to server
NSData *imageData = UIImageJPEGRepresentation(uploadImageHidden.image, 90);
NSString *urlStringOne = #"http://myflashpics.com/iphone_processes/upload.php?album=";
NSString *urlStringTwo = #"&id=";
NSString *urlString = [NSString stringWithFormat:#"%#%#%#%#",urlStringOne,getAlbumID,urlStringTwo,theUserID];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"userfile\"; filename=\".jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
//NSLog(#"%#", returnString);
if ([returnString rangeOfString:#"yes"].location == NSNotFound) {
// Fail
} else {
// Delete image if successful
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *myFilePath = [documentsDirectoryPath stringByAppendingPathComponent:sqlImageUploadPathTwo];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:myFilePath error:NULL];
[database executeNonQuery:#"DELETE FROM processes WHERE image=?", sqlImageUploadPathTwo];
// Get Photo ID
NSArray *myWords = [returnString componentsSeparatedByString:#" "];
NSString *photoID = [myWords objectAtIndex:1];
NSString *usernameID = [myWords objectAtIndex:2];
NSString *defaultName = #"Photo uploaded from the flashpics iPhone application";
// Get Thumbnail URL
NSString *thumbnailURLOne = #"http://myflashpics.com/users/";
NSString *thumbnailURLTwo = #"/pictures/thumbnails/";
NSString *thumbnailURLThree = #".jpg";
NSString *thumbnailURL = [NSString stringWithFormat:#"%#%#%#%#%#",thumbnailURLOne,usernameID,thumbnailURLTwo,photoID,thumbnailURLThree];
// Download thumbnail
//NSLog(#"Downloading...");
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:thumbnailURL]]];
//NSLog(#"%f,%f",image.size.width,image.size.height);
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//NSLog(#"%#",docDir);
//NSLog(#"saving jpeg");
NSString *jpegFilePath = [NSString stringWithFormat:#"%#/%#_thumbnail.jpg",docDir,photoID];
NSData *data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 0.2f)];//1.0f = 100% quality
[data2 writeToFile:jpegFilePath atomically:YES];
//NSLog(#"saving image done");
[image release];
// Put in database
NSString *thumbnailEnd = #"_thumbnail.jpg";
NSString *thumbnailLocation = [NSString stringWithFormat:#"%#%#",photoID,thumbnailEnd];
int theCount = 0;
NSArray *getUserIDInfotoo = [database executeQuery:#"SELECT * FROM images WHERE id=?",photoID];
for (NSDictionary *getUserIDRowtoo in getUserIDInfotoo) {
theCount++;
}
if (theCount == 0) {
[database executeNonQuery:#"INSERT INTO images (id, name, thumbnail, album) VALUES (?, ?, ?, ?)", photoID, defaultName, thumbnailLocation, getAlbumID];
}
//[NSThread detachNewThreadSelector:#selector(updateImages) toTarget:RootViewController withObject:nil];
//myTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector: #selector(updateImages) userInfo: nil repeats: NO];
}
[request release];
[returnString release];
}
//NSLog([rowtwo valueForKey:#"image"]);
//NSLog([rowtwo valueForKey:#"album"]);
}
[pool release];
// Stop the UIActivity in the top bar
TableViewAppDelegate *dataCeter = (TableViewAppDelegate *)[[UIApplication sharedApplication] delegate];
if ([dataCeter.dataTen isEqualToString:#""]) {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
}
Edit 2:
Where the startUploads gets called (different .m)
processViewController *processTable = [[processViewController alloc] initWithNibName:#"processView.xib" bundle:nil];
[processTable startUploads];
[processTable release];
More code would be helpful but here are some suggestions:
Check if startUploads is being called before the view is loaded. The view will only be loaded when it is accessed for the first time to be added to a superview.
Consider initializing processList in your init method instead of viewDidLoad both to solve #1 and b/c the view can loaded & unloaded by iOS independently of the lifecycle of the viewController (depending on what other views you are displaying and whether any memory warnings occur).
Make sure you are releasing processList in dealloc. You only need to release it in viewDidUnload if it is recreated and loaded in viewDidLoad.
Your code sample doesn't show when startUploads is being called and you aren't adding any items to processList so it's hard to tell if the above is relevant. Post some more code and I'll revise my answer accordingly.
good luck!
[EDIT: added example code]
The code fragments you posted are not a complete implementation of a view controller and the associated objects that interact with it. Given the code I have seen, your application design does not conform to MVC (Model/View/Controller) design pattern and I would be doing things a bit differently. However, I don't want to make assumptions about code I haven't seen or your ultimate intent or ability as a developer. I can't write your app for you, just trying to directly help you with the specific question you asked regarding why your NSMutableArray property remains null after the startUploads action completed. With that in mind, here are my edits to the code you posted:
processViewController.m - add the following:
- (id)initWithNibNamed:(NSString *)nibName bundle:(NSBundle *)bundle {
self = [super initWithNibNamed:nibName bundle:bundle];
if (self) {
processList = [[NSMutableArray alloc] init];
}
return self;
}
- (void)dealloc {
self.processList = nil;
[super dealloc];
}
different.m
- (void)displayProcessVC {
ProcessViewController *processVC = [[ProcessViewController alloc] initWithNibNamed:#"processView.xib" bundle:nil];
NSLog(#"Different:displayProcessVC BEFORE STARTING UPLOAD, processList = %#", processVC.processList);
[processVC startUploads];
NSLog(#"Different:displayProcessVC AFTER STARTING UPLOAD, processList = %#", processVC.processList);
// would normally present process VC here
[processVC release];
}
Hope this helps.

upload plist file on server in iphone

i have created a plist file other than the default one that exists.
Can i upload this plist file onto the server
I tried ASIFormDataRequest.
I was able to upload the image and text file but when i try it with plist it throws error at point shown in bold:
Code:
networkQueue = [[ASINetworkQueue queue] retain];
NSString *filePath = [[[NSBundle mainBundle]
resourcePath] stringByAppendingPathComponent:
[#"test" stringByAppendingString:#".plist"]];
ASIFormDataRequest *request =[ASIFormDataRequest
requestWithURL:[NSURL URLWithString:#"http://allseeing-i.com/ignore"]];
[request setPostValue:#"my_test" forKey:#"share_test"];
[request setFile:filePath
withFileName:[test stringByAppendingString:
#".plist"] andContentType:#"propertylist/plist" forKey:#"mytest"];
[request setDelegate:self];
[request setDidFailSelector:#selector(requestFailed:)];
[request setDidFinishSelector:#selector(gotTheResponse:)];
[networkQueue addOperation: request];
[networkQueue go];
is it really possible?
or should i go ahead with xml
though plist is also an xml format
but still i want to know and what should i do?
networkQueue = [[ASINetworkQueue queue] retain];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
dateString = [formatter stringFromDate:[NSDate date]];
[formatter release];
// hyphen(-) joins file name with the timestamp for uniqueness
NSString *theme_name1 = [[[theme_name stringByAppendingString:#"-"]
stringByAppendingString:dateString]
stringByReplacingOccurrencesOfString:#" " withString:#"_" ];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *path = [documentsPath stringByAppendingPathComponent:
[file_name stringByAppendingString:#".plist"]];
id plist = [[NSDictionary alloc] initWithContentsOfFile:path];
NSData *xmlData = [NSPropertyListSerialization dataFromPropertyList:plist
format:NSPropertyListXMLFormat_v1_0 errorDescription:nil];
NSString *xml_string = [[NSString alloc] initWithData:xmlData
encoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:#"myurl"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:#"file_name1 forKey:#"filename"];
[request setPostValue:#"user" forKey:#"sharedby"];
[request setPostValue:xml_string forKey:#"data"];
[request setUsername:#"hello"];
[request setPassword:#"world"];
[request setDelegate:self];
[request setDidFailSelector:#selector(requestFailed:)];
[request setDidFinishSelector:#selector(gotTheResponse:)];
[networkQueue addOperation:request];
[networkQueue go];
I got mine to work. Hope this helps somebody :)
NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:
[#"test" stringByAppendingString:#".plist"]];
NSDictionary *plist = [[NSDictionary alloc] initWithContentsOfFile:path];
NSData *data = [NSPropertyListSerialization dataFromPropertyList:plist format:NSPropertyListXMLFormat_v1_0 errorDescription:nil];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:#"yourUrl"]];
[request addData:data withFileName:#"test.plist" andContentType:#"propertylist/plist" forKey:#"file"];
[request setDelegate:self];
[request startAsynchronous];
If you are correct that xml and text files are fine with the above code then the most likely explanation would seem to be that either the path to the plist file is incorrect, or the file permissions don't allow the file to be read.
You can enable debug in ASIHTTPRequestConfig.h that might reveal more about what's going on.