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.
Related
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);
}
im new with objective-c. I have problem with memory leaking when developing iphone app. Leaking utility in Xcode shows that leaking problem with 'combArr'->'results' object. There is my function which parsing json from url and returns NSArray:
- (NSArray *)getListing2:(NSString *)item
from:(int)country {
//sending post request with some params
NSString *post = [#"product=" stringByAppendingString:item];
NSString *countryStr = [NSString stringWithFormat:#"&country=%d", country];
post = [post stringByAppendingString:countryStr];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *url = [prefs objectForKey:#"urlToApi"];
url = [url stringByAppendingString:#"/get-items/"];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
[request release];
//receiving json
NSString *jsonString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
SBJsonParser *json = [[SBJsonParser alloc] init];
NSError *error = nil;
//parsing json to nsdictionary
NSDictionary *results = [[NSDictionary alloc] initWithDictionary:[json objectWithString:jsonString error:&error]];
[json release];
[jsonString release];
//generate array of items
NSMutableArray *listOfItems = [[NSMutableArray alloc] init];
for (int i = 0; i < [[results objectForKey:#"data"] count]; i++) {
[listOfItems addObject:[[results objectForKey:#"data"] objectForKey:[NSString stringWithFormat:#"%d", i]]];
}
//saving items array and count info object into one array
NSArray * returnArr = [[[NSArray arrayWithObjects:listOfItems, [results valueForKey:#"count_info"], nil] retain] autorelease];
[listOfItems release];
[results release];
return returnArr;
}
And i executing this function here:
myApi *itemsApi = [[myApi alloc] init];
NSArray *combArr = [[izdApi getListing2:item from:countryId] retain];
[itemsApi release];
listOfItems = [[combArr objectAtIndex:0] retain];
if([listOfItems count] > 0){
priceArr = [[combArr objectAtIndex:1] retain];
}
else{
totalCount = 0;
}
[combArr release];
Thank you for helping
Every time you allocate memory, you must release it. (alloc, copy, retain).
You are releasing myApi, not itemsApi. Try this...
myApi *itemsApi = [[itemsApi alloc] init];
NSArray *combArr = [[izdApi getListing2:item from:countryId] retain];
[itemsApi release];
listOfItems = [[combArr objectAtIndex:0] retain];
if([listOfItems count] > 0){
priceArr = [[combArr objectAtIndex:1] retain];
}
else{
totalCount = 0;
}
[combArr release];
If you are using Xcode 4, Try turning on ARC. In short, ARC handles the releasing of all memory. A little burden off your shoulders and one less thing for you to worry about.
using this method to post the image
- (void)postInAppFacebook {
btnForLogout.hidden=NO;
NSMutableDictionary *variables = [NSMutableDictionary dictionaryWithCapacity:3];
NSData *imageData = UIImageJPEGRepresentation(imgPicture.image, 4.0);
UIImage *picture = [[UIImage alloc]initWithData:imageData];
FbGraphFile *graph_file = [[FbGraphFile alloc] initWithImage:picture];
[variables setObject:graph_file forKey:#"file"];
[variables setObject:[NSString stringWithFormat:#"%#", txtComment.text] forKey:#"message"];
**[fbGraph doGraphPost:#"me/photos" withPostVars:variables];**
NSLog(#"Now log into Facebook and look at your profile & photo albums...");
UIAlertView *alertForImageHasPost=[[UIAlertView alloc]initWithTitle:#"MAP IMAGE POST" message:#"SELECTED IMAGE POSTED" delegate:self cancelButtonTitle:#"CANCEL" otherButtonTitles:#"OK",nil];
[alertForImageHasPost show];
[alertForImageHasPost release];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
problem in this method
second time its crash but working well in simulator
- (FbGraphResponse *)doGraphPost:(NSString *)action withPostVars:(NSDictionary *)post_vars {
NSLog(#"action is %#",action);
FbGraphResponse *return_value = [[FbGraphResponse alloc] init];
NSString *urlString = [NSString stringWithFormat:#"https://graph.facebook.com/%#", action];
NSURL *url = [NSURL URLWithString:urlString];
NSString *boundary = #"----1010101010";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSEnumerator *enumerator = [post_vars keyEnumerator];
NSString *key;
NSString *value;
NSString *content_disposition;
//loop through all our parameters
while ((key = (NSString *)[enumerator nextObject])) {
//if it's a picture (file)...we have to append the binary data
if ([key isEqualToString:#"file"]) {
/*
* the FbGraphFile object is smart enough to append it's data to
* the request automagically, regardless of the type of file being
* attached
*/
FbGraphFile *upload_file = (FbGraphFile *)[post_vars objectForKey:key];
[upload_file appendDataToBody:body];
//key/value nsstring/nsstring
} else {
value = (NSString *)[post_vars objectForKey:key];
content_disposition = [NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", key];
[body appendData:[content_disposition dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[value dataUsingEncoding:NSUTF8StringEncoding]];
}//end else
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
}//end while
//add our access token
[body appendData:[#"Content-Disposition: form-data; name=\"access_token\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[accessToken dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//button up the request body
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request addValue:[NSString stringWithFormat:#"%d", body.length] forHTTPHeaderField: #"Content-Length"];
//quite a few lines of code to simply do the business of the HTTP connection....
NSURLResponse *response;
NSData *data_reply;
NSError *err;
**//crash after this line**
***
> data_reply = [NSURLConnection sendSynchronousRequest:request
> returningResponse:&response error:&err];
***
return_value.htmlResponse = (NSString *)[[NSString alloc] initWithData:data_reply encoding:NSUTF8StringEncoding];
if (err != nil) {
return_value.error = err;
}
/*
* return the json array. we could parse it, but that would incur overhead
* some users might not want (not to mention dependencies), besides someone
* may want raw strings back, keep it simple.
*
* See: http://code.google.com/p/json-framework for an easy json parser
*/
return return_value;
}
Have a look at below functions. I hope you will get success with it.
Please have a look at all the methods as below:
- (IBAction)uploadPhoto:(id)sender {
[self postOnFacebook];
}
//Post Message and Photos on Facebook Function
-(void)postOnFacebook
{
NSString *strPostMessage = [self createMessageForPostOnFacebook:74.112 withLongitude:21.85];
//UIImage *img = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:objClsProductSearch.strProductImageURL]]];
//UIImage *img = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.facebook.com/images/devsite/iphone_connect_btn.jpg"]]];
UIImage *img = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://d1xzuxjlafny7l.cloudfront.net/wp-content/uploads/2011/08/HUDTutorial.jpg"]]];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
strPostMessage,#"message",img, #"source",
nil];
[_facebook requestWithGraphPath:#"/me/photos"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
[img release];
}
//Create Message for posting on Facebook
-(NSString *)createMessageForPostOnFacebook:(double)pfltLatitude withLongitude:(double)pfltLongitude
{
//NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%f,%f&output=csv",pfltLatitude, pfltLongitude];
//NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%f,%f&output=csv",#"", #""];
//NSError* error;
//NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
//NSArray *listItems = [locationString componentsSeparatedByString:#","];
NSString *strMessage = nil;
/*if([[listItems objectAtIndex:0] isEqualToString:#"200"])
{
strMessage = [NSString stringWithFormat:#"I found a %# using BH for iPhone \n Location : %# \n Latitude : %f & Longitude : %f \n Product Rating : %d",objClsProductSearch.strCategoryname,[locationString substringFromIndex:6],appDelegate.dblLatitude,appDelegate.dblLongitude,btnTmp.tag];
}*/
strMessage = [NSString stringWithFormat:#"I found a %# using BH for iPhone \n Location : %# \n Latitude : %f & Longitude : %f \n Product Rating : %d", #"Cat Name", #"Location", 74.112, 21.85, 1];
return strMessage;
}
I hope you will have success using the above code.
Let me know in case of any difficulty.
In you app delegate, have a look at below methods whether it is implemented or not.
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
//return [[controller facebook] handleOpenURL:url];
//return [[objPage2ViewController facebook] handleOpenURL:url];
return [[[self.navigationController topViewController] facebook] handleOpenURL:url];
}
Cheers
I have the following problem:
in header;
GDataXMLDocument *doc;
NSString *xmlBody;
#property (nonatomic,copy) NSString *xmlBody;
#property (nonatomic,retain) GDataXMLDocument *doc;
in m
#import "tchLoader.h"
#import "Variable.h"
#import "DisplayVariable.h"
#implementation tchLoader
#synthesize responseXMLData,lastLoadedResponseXMLData;
#synthesize conn;
#synthesize doc;
#synthesize xmlBody;
- (void)loadXML:(id<tchLoaderDelegate>)delegate {
NSString *theBaseXML= #"some xml code here"
if (self.xmlBody==nil){
self.xmlBody=theBaseXML;
}
_delegate = delegate;
/*
SCNetworkReachabilityFlags flags;
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, [#"www.alues.com" UTF8String]);
SCNetworkReachabilityGetFlags(reachability, &flags);
// The reachability flags are a bitwise set of flags that contain the information about
// connection availability
BOOL reachable = ! (flags & kSCNetworkReachabilityFlagsConnectionRequired);
*/
NSString *soapMessage =self.xmlBody;
NSURL *url = [NSURL URLWithString:#"https://area.tch-values.com/soapmwp/mws"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
[request addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request addValue: #"http://www.tch-values.com/webservice" forHTTPHeaderField:#"SOAPAction"];
[request addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
if ([NSURLConnection canHandleRequest:request] && true) {
self.conn = [[NSURLConnection alloc ]initWithRequest:request delegate:self];
if (self.conn) {
self.responseXMLData = [NSMutableData data];
}
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"ERROR with theConenction");
[self.doc release];
[self.conn release];
[self.responseXMLData release];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"DONE. Received Bytes: %d", [self.responseXMLData length]);
//[self.conn release];
if ([_delegate respondsToSelector:#selector(xmlDidFinishLoading)]) {
[_delegate xmlDidFinishLoading];
}
}
-(void)insertAnswers: (NSMutableArray*) answeredVariables{
for (Variable * variable in answeredVariables)
{
NSInteger pageID=[variable pageId];
//NSMutableArray *answers=[NSMutableArray arrayWithCapacity:[[variable variableValues] count]];
NSString *path = [NSString stringWithFormat:#"//inferenceresponse/state/variable[pageId=%d]/valuedefinition",pageID];
NSArray *valueElement = [doc nodesForXPath:path error:nil];
GDataXMLElement *valueDefinitionElement;
if (valueElement.count > 0) {
valueDefinitionElement= (GDataXMLElement *) [valueElement objectAtIndex:0];
}
GDataXMLElement * sourceElement = [GDataXMLNode elementWithName:#"source"];
[sourceElement addAttribute:[GDataXMLNode attributeWithName:#"type" stringValue:#"ask user"]];
GDataXMLElement * timeStampElement = [GDataXMLNode elementWithName:#"timestamp" stringValue:#"12345"];
[sourceElement addChild:timeStampElement];
GDataXMLElement * assignmentElement = [GDataXMLNode elementWithName:#"assignmentnumber" stringValue:#"6"];
for(NSString *answer in variable.variableValues){
GDataXMLElement * variableValueElement = [GDataXMLNode elementWithName:#"variablevalue"];
[variableValueElement addAttribute:[GDataXMLNode attributeWithName:#"value" stringValue:answer]];
[valueDefinitionElement addChild:variableValueElement];
}
[valueDefinitionElement addChild:sourceElement];
[valueDefinitionElement addChild:assignmentElement];
}
NSData *xmlData = self.doc.XMLData;
NSString *theXML = [[NSString alloc] initWithBytes:[xmlData bytes] length:[xmlData length] encoding:NSUTF8StringEncoding];
theXML =[theXML stringByReplacingOccurrencesOfString:#"inferenceresponse" withString:#"inferencerequest"];
theXML =[theXML stringByReplacingOccurrencesOfString:#"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">" withString:#"<SOAP-ENV:Envelope xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"> "];
theXML =[theXML stringByReplacingOccurrencesOfString:#"xmlns=\"\"" withString:#"xmlns=\"http://www.tch-values.com/xml/webservice\""];
theXML =[theXML stringByReplacingOccurrencesOfString:#"<state goalreached=\"false\">" withString:#"<state goalreached=\"false\"> <value>PlanKB</value> <goalvariable>myGoal</goalvariable> "];
self.xmlBody=theXML;
[theXML release];
//[self.doc release];
NSLog(self.xmlBody);
}
- (NSMutableArray*)variablesForPageID:(NSString*)pageID {
NSMutableArray *variables = nil;
if (self.responseXMLData) {
variables = [NSMutableArray arrayWithCapacity:10];
NSData *xmlData = self.responseXMLData;
NSError *error;
self.doc=nil;
doc = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&error];
if (self.doc == nil) {
return nil;
}
NSArray *status = [doc nodesForXPath:#"//inferenceresponse/state[#goalreached='true']" error:nil];
if([status count]==1){
self.xmlBody=nil;
Variable *variable=[[Variable alloc] init];
NSString *path = [NSString stringWithFormat:#"//inferenceresponse/state/displayvariables/display[#isDisplayShown='false']"];
NSArray *displayVariablesElements = [doc nodesForXPath:path error:nil];
NSMutableArray *disps=[[NSMutableArray alloc] init];
if(displayVariablesElements.count >0){
for(GDataXMLElement *disElement in displayVariablesElements){
DisplayVariable *disVar=[[DisplayVariable alloc] init];
NSArray *disPageid = [disElement nodesForXPath:#"#displayPageId" error:nil];
GDataXMLElement *Pageid = (GDataXMLElement *) [disPageid objectAtIndex:0];
disVar.displayPageId =Pageid.stringValue;
NSArray *disName = [disElement nodesForXPath:#"displayname" error:nil];
if(disName.count >0){
GDataXMLElement *disNam = (GDataXMLElement *) [disName objectAtIndex:0];
disVar.displayName =disNam.stringValue;
}
NSArray *disValue = [disElement nodesForXPath:#"displayvalue" error:nil];
if(disValue.count >0){
GDataXMLElement *disVal = (GDataXMLElement *) [disValue objectAtIndex:0];
disVar.displayValue =disVal.stringValue;
}
NSArray *disId = [disElement nodesForXPath:#"#id" error:nil];
GDataXMLElement *disIdEl = (GDataXMLElement *) [disId objectAtIndex:0];
disVar.pageId =[disIdEl.stringValue intValue];
[disps addObject:disVar];
[disVar release];
}
variable.displayVariables=disps;
[disps release];
}
variable.lastVariableofConsultation=YES;
[variables addObject:variable];
[variable release];
}
else{
NSArray *inferenceMembers = [doc nodesForXPath:#"//inferenceresponse/state/variable[not(valuedefinition/variablevalue)]" error:nil];
for (GDataXMLElement *variableElement in inferenceMembers) {
Variable *variable=[[Variable alloc] init];
NSArray *items = [variableElement nodesForXPath:#"domaindefinition/domain/enumType/domainitem" error:nil];
NSMutableArray *domainItems = [NSMutableArray arrayWithCapacity:items.count];
for (int i=0; i<items.count;i++) {
GDataXMLElement *domainItem = (GDataXMLElement *) [items objectAtIndex:i];
[domainItems addObject:domainItem.stringValue];
}
variable.domainItems=domainItems;
NSArray *names = [variableElement nodesForXPath:#"name/#name" error:nil];
if (names.count > 0) {
GDataXMLElement *nameElement = (GDataXMLElement *) [names objectAtIndex:0];
variable.variableName = nameElement.stringValue;
}
NSArray *pageId = [variableElement nodesForXPath:#"pageId" error:nil];
}
}
return variables;
}
- (void)dealloc {
[responseXMLData release] ;
[lastLoadedResponseXMLData release] ;
[conn release];
[doc release];
[xmlBody release];
[super dealloc];
}
#end
#import "tchLoader.h"
#import "Variable.h"
#import "DisplayVariable.h"
#implementation tchLoader
#synthesize responseXMLData,lastLoadedResponseXMLData;
#synthesize conn;
#synthesize doc;
#synthesize xmlBody;
If I [theXML release] it crashes, If I dont release theXML then it works perfect but I see memory leak in simulator Instruments tool. (There are also lots of memory leaks I see in this code but couldnt figure out by instrumnets tool what is going on)
This looks wrong:
[doc release];
Why are you releasing an object managed by a property?
In your #synthesize statements change them to:
#synthesize doc = doc_;
#synthesize xmlBody = xmlBody_;
Then fix all the resulting errors to go through the property, releasing the properties ONLY in dealloc.
Edit:
You say it crashes releasing theXML. This code is wrong:
NSString *theXML = [[NSString alloc] initWithBytes:[xmlData bytes] length:[xmlData length] encoding:NSUTF8StringEncoding];
theXML =[theXML stringByReplacingOccurrencesOfString:#"inferenceresponse" withString:#"inferencerequest"];
[theXML release];
You alloc a string, replace that variable with the "stringByReplacing..." call with a string that is autoreleased, then try to release the resulting string that is autoreleased which will crash. When you don't need to keep a string around after the method you are in, ALWAYS use autorelease. The correct code is:
NSString *theXML = [[[NSString alloc] initWithBytes:[xmlData bytes] length:[xmlData length] encoding:NSUTF8StringEncoding] autorelease];
theXML =[theXML stringByReplacingOccurrencesOfString:#"inferenceresponse" withString:#"inferencerequest"];
And take out [theXML release] - there will be no leak.
I think you should really switch to using ARC as soon as you possibly can... it will save you from a lot of such misunderstandings.
If you want to release an ivar/property(retain), this is not how to to it:
[self.doc release];
instead:
self.doc = nil;
One "problem" with singleton objects is that they appear to leak. If you create an object and never destroy it, Instruments says it's a leak, even if your intention was never to release it.
NSData *xmlData = doc.XMLData;
newXML = [[NSString alloc] initWithBytes:[xmlData bytes] length:[xmlData length]
encoding:NSUTF8StringEncoding];
What is your newXML? is it a ivar and synthesize it and retain it? if yes the compiler will automatically generate getter and setter methods.
NSData *xmlData = doc.XMLData;
self.newXML = [[NSString alloc] initWithBytes:[xmlData bytes] length:[xmlData length]
encoding:NSUTF8StringEncoding];
self.timestamp = nil;
If its not property then
NSString* newXML = [[NSString alloc] initWithBytes:[xmlData bytes] length:[xmlData length]
encoding:NSUTF8StringEncoding];
self.xmlBody=newXML;
[newXML release];
I'm trying to fetch images from url. Can someone point where i get wrong here is my code?
NSString *filesContent = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://www.projects-demo.com/iphone/xml/Menu.xml"] ];
DDXMLDocument *ddDoc = [[DDXMLDocument alloc] initWithXMLString:filesContent options:0 error:nil];
DDXMLElement *ddMenu = [ddDoc rootElement];
NSArray *ddChildren = [ddMenu children];
for (int j = 0 ;j < [ddChildren count]; j++) {
DDXMLElement *image1st = [[ddMenu elementsForName:[NSString stringWithFormat:#"cookingType%d",j+1]] objectAtIndex:0];
for (DDXMLNode *n in [image1st children]) {
// if ([[n name] isEqualToString: #"cookingType"]) {
MenuModel *model = [[MenuModel alloc] init];
NSLog(#"image of cooking........%#",[n stringValue]);
model.imgsrc = [n stringValue];
[listofimages addObject:model];
//ss
//======
NSData *mydata = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:model.imgsrc]];
NSLog(#"printing my data ....",mydata);
UIImage *myimage = [[UIImage alloc] initWithData:mydata];
I tried to print nsDAta but it get nothing.
Just an observation, your NSLog for the variable myData, misses %#, not sure if this is just a copy and paste error or something that the HTML doesn't show.
Also try and Log [myData length] there might be a problem with the download.
Last, I would recommend that you do all your URL calls asynchronously.
It would look somewhat like this
`
-(void) loadingThumnailFormURL:(NSString *) thumbnailURL {
[imageData release];
imageData = [[NSMutableData alloc] init];
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:thumbnailURL]];
NSURLConnection *urlConnection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
[urlRequest release];
[urlConnection start];
}`
Needless to say you have to implement the delegate methods for NSURLConnection and capture the data.