NSURL *url=[NSURL URLWithString:elementurl];
NSLog(#"url %#", url);
NSData *data = [NSData dataWithContentsOfURL:url];
NSLog(#"data = %#, length = %i", data, [data length]);
UIImage *image = [[UIImage alloc] initWithData:data];
[data release];
iam not getting the data can any one suggest another method
pragma mark --------------------------
pragma mark Load UserImage
-(void)loadUserImage{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *frameImagePath = [profileInfoDict objectForKey:#"photo"];
imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:frameImagePath]];
if([imageData length] == 0){
/*NSString *imagePath = [[NSString alloc] initWithFormat:#"%#/%#",[[NSBundle mainBundle] resourcePath],#"no_image.png"];
UIImage image = [[UIImage alloc] initWithContentsOfFile:imagePath];
[item setObject:image forKey:#"itemImage"];
[imagePath release];
[image release];/
}
else {
[self performSelectorOnMainThread:#selector(imageget:) withObject:imageData waitUntilDone:NO];
}
[pool release];
}
-(void)imageget:(NSData *)data
{
UIImage *image = [[UIImage alloc] initWithData:data];
userImageImageView.contentMode = UIViewContentModeScaleAspectFit;
userImage=image;
userImageImageView.image = image;
[[mAppDelegate.userInfoArray objectAtIndex:1] setValue:image forKey:#"Image"];
}
The method you have used is good for small images. If you are trying to download big images it will not do it properly.
You can use the below code
NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
To establish connection
(void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData
(void)connectionDidFinishLoading:(NSURLConnection*)theConnection
(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
and above method is used to receive data, error handling etc...
Now apply your own logic by using this methods.
Related
I am trying to load web content asynchronously. I have a large amount of web calls in my viewdidappear method and my app is very unresponsive. I understand the concepts of synchronous and asynchronous loading of content, but don't know how to tell if this is being done asynchronously. The code below is simply embedded in my viewdidappear method, and I assume it is loading synchronously. How would I edit this to make it load asynchronously? Thank you all!
NSString *strURLtwo = [NSString stringWithFormat:#"http://website.com/json.php?
id=%#&lat1=%#&lon1=%#",id, lat, lon];
NSData *dataURLtwo = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURLtwo]];
NSArray *readJsonArray = [NSJSONSerialization JSONObjectWithData:dataURLtwo options:0
error:nil];
NSDictionary *element1 = [readJsonArray objectAtIndex:0];
NSString *name = [element1 objectForKey:#"name"];
NSString *address = [element1 objectForKey:#"address"];
NSString *phone = [element1 objectForKey:#"phone"];
You can use NSURLConnectionDelegate:
// Your public fetch method
-(void)fetchData
{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://website.com/json.php?id=%#&lat1=%#&lon1=%#",id, lat, lon]];
// Put that URL into an NSURLRequest
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
// Create a connection that will exchange this request for data from the URL
connection = [[NSURLConnection alloc] initWithRequest:req
delegate:self
startImmediately:YES];
}
Implement the delegate methods:
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
// Add the incoming chunk of data to the container we are keeping
// The data always comes in the correct order
[jsonData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
// All data is downloaded. Do your stuff with the data
NSArray *readJsonArray = [NSJSONSerialization jsonData options:0 error:nil];
NSDictionary *element1 = [readJsonArray objectAtIndex:0];
NSString *name = [element1 objectForKey:#"name"];
NSString *address = [element1 objectForKey:#"address"];
NSString *phone = [element1 objectForKey:#"phone"];
jsonData = nil;
connection = nil;
}
// Show AlertView if error
- (void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error
{
connection = nil;
jsonData = nil;
NSString *errorString = [NSString stringWithFormat:#"Fetch failed: %#", [error localizedDescription]];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:errorString delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alertView show];
}
For asynchronous web content loading, I recommend you to use AFNetworking . It'll solve lots of your major headache of networking in future. How to do:
1) subclass AFHTTPCLient, for example:
//WebClientHelper.h
#import "AFHTTPClient.h"
#interface WebClientHelper : AFHTTPClient{
}
+(WebClientHelper *)sharedClient;
#end
//WebClientHelper.m
#import "WebClientHelper.h"
#import "AFHTTPRequestOperation.h"
NSString *const gWebBaseURL = #"http://whateverBaseURL.com/";
#implementation WebClientHelper
+(WebClientHelper *)sharedClient
{
static WebClientHelper * _sharedClient = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:gWebBaseURL]];
});
return _sharedClient;
}
- (id)initWithBaseURL:(NSURL *)url
{
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
[self registerHTTPOperationClass:[AFHTTPRequestOperation class]];
return self;
}
#end
2) Request asynchronously your web content, put this code in any relevant part
NSString *testNewsURL = #"http://whatever.com";
NSURL *url = [NSURL URLWithString:testNewsURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operationHttp =
[[WebClientHelper sharedClient] HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSString *szResponse = [[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"Response: %#", szResponse );
//PUT your code here
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Operation Error: %#", error.localizedDescription);
}];
[[WebClientHelper sharedClient] enqueueHTTPRequestOperation:operationHttp];
The problem is like, when the image size is more than 60 kb, it is not posting the image to the web service , but if the image size is less than 60 kb, its posting to the web service.
How to decrease the size of the Image in objective c.
The following is the code which i am using,
-(IBAction)sendEmail:(id)sender
{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSLog(#"TABLEDIC%#",appDelegate.tableDic);
//Parsing
recordResults = FALSE;
NSString *soapMessage = [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
"<soap:Body>\n"
"<CreateTextMail xmlns=\"http://tempuri.org/\">\n"
"<listid>%#</listid>\n"
"<fromid>%#</fromid>\n"
"<subject>%#</subject>\n"
"<replyto>%#</replyto>\n"
"<loginid>%#</loginid>\n"
"<fromname>%#</fromname>\n"
"<forward>%#</forward>\n"
"<subscribe>%#</subscribe>\n"
"<mailpriority>%#</mailpriority>\n"
"<recievermailtext>%#</recievermailtext>\n"
"<mailbody>%#</mailbody>\n"
"<emailname>%#</emailname>\n"
"<signature>%#</signature>\n"
"<listname>%#</listname>\n"
"<emailtype>%#</emailtype>\n"
"<imagecontent>%#</imagecontent>\n"
"<imagename>%#</imagename>"
"</CreateTextMail>\n"
"</soap:Body>\n"
"</soap:Envelope>\n",[appDelegate.tableDic valueForKey:#"tableID"],[appDelegate.tableDic valueForKey:#"fromname"],[appDelegate.tableDic valueForKey:#"subject"],[appDelegate.tableDic valueForKey:#"replyto"],[appDelegate.tableDic valueForKey:#"loginid"],[appDelegate.tableDic valueForKey:#"fromname"],forward.text,subscribe.text,[appDelegate.tableDic valueForKey:#"mailpriority"],receivermailtext.text,body.text,[appDelegate.tableDic valueForKey:#"emailName"],[appDelegate.tableDic valueForKey:#"signature"],[appDelegate.tableDic valueForKey:#"tableName"],emailType,strEncoded,imageName.text
];
NSLog(#"SOPA%#",soapMessage);
NSURL *url = [NSURL URLWithString:#"http://www.xxx.net/xxx/xxx.asmx"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d",[soapMessage length]];
[theRequest addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue:#"http://tempuri.org/CreateTextMail" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody:[soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
NSHTTPURLResponse *urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Response Code : %d",[urlResponse statusCode]);
if([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300)
{
NSLog(#"Response: %#",result);
}
if( theConnection )
{
webData = [NSMutableData data];
}
else
{
NSLog(#"theConnection is NULL");
}
[subject resignFirstResponder];
[replyto resignFirstResponder];
[loginid resignFirstResponder];
[fromname resignFirstResponder];
[emailName resignFirstResponder];
[signature resignFirstResponder];
[listName resignFirstResponder];
}
-(void)takeCamera
{
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
NSLog(#"take a photo");
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = (id)self;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.mediaTypes = [NSArray arrayWithObjects:(NSString *)kUTTypeImage, nil];
imagePicker.allowsEditing = NO;
[self presentModalViewController:imagePicker animated:YES];
newMedia = YES;
}
}
-(void)pickCameraRoll
{
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum])
{
UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
imagePicker.delegate = (id)self;
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.mediaTypes = [NSArray arrayWithObjects:(NSString *)kUTTypeImage, nil];
imagePicker.allowsEditing = NO;
[self presentModalViewController:imagePicker animated:YES];
newMedia = NO;
}
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
[self dismissModalViewControllerAnimated:YES];
if([mediaType isEqualToString:(NSString *)kUTTypeImage])
{
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
imageView.image = image;
NSData *myData = UIImagePNGRepresentation(image);
// NSLog(#"NSData : %#",myData);
[Base64 initialize];
strEncoded = [Base64 encode:myData];
NSLog(#"strEncoded : %#",strEncoded);
if(newMedia)
UIImageWriteToSavedPhotosAlbum(image, self, #selector(image:finishedSavingWithError:contextInfo:), nil);
NSLog(#"image pick");
}
else if ([mediaType isEqualToString:(NSString *)kUTTypeImage])
{
}
}
-(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];
}
What would be the problem in the device,where it is failing to send the image to the web service, but able to send successfully in the iphone simulator.
Any suggestions would be very helpful.
Thanks in advance.
For decompressing image use following code, It loops untill the image size reduces to maximum image size.
CGFloat maxCompressionFactor = 0.1f;
CGFloat compressionFactor = 0.9f;
int maxImageSize = 60 * 1024;
NSData *imageData = UIImageJPEGRepresentation(image, compressionFactor);
while ([imageData length] > maxImageSize && compressionFactor > maxCompressionFactor)
{
compressionFactor -= 0.1;
imageData = UIImageJPEGRepresentation(image, compressionFactor);
}
The size of image can be reduced by increasing the compression with the sacrifice of image quality.
Use: UIImageJPEGRepresentation
UIImage *compressedImage = UIImageJPEGRepresentation(theImage, 0.5);
After processing the XML data (read xml data and insert sqlite reading data....etc), I'd like to move to the next view.
How can I check whether it is finished parsing the XML?
I attach my code. Where can I check if parsing has finished?
-(IBAction)clickServerSync:(id)sender
{
if ([util checkNetwork]) {
[self LoadXml:#"LANG"];
[self LoadXml:#"CATEGORY"];
[self LoadXml:#"LIST"];
[self LoadXml:#"FILE"];
}
}
-(void)LoadXml:(NSString*)P_VAL
{
[indicator setHidden:NO];
NSString *smsURL = [NSString stringWithFormat:#"%#%#.asp", XML_URL, P_VAL];
NSString *sendAuthInfo = [NSString stringWithFormat:#"xx=%d" , 0 ];
NSString *val = [sendAuthInfo stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:smsURL]]autorelease];
[request setURL:[NSURL URLWithString:smsURL]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: [val dataUsingEncoding:NSUTF8StringEncoding]];
[self startAsyncLoad:request tag:P_VAL];
}
- (void)startAsyncLoad:(NSMutableURLRequest*)request tag:(NSString*)tag {
CustomURLConnection *connection = [[CustomURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES tag:tag];
if (connection) {
[receivedData setObject:[[NSMutableData data] retain] forKey:connection.tag];
}
}
- (NSMutableData*)dataForConnection:(CustomURLConnection*)connection {
NSMutableData *data = [receivedData objectForKey:connection.tag];
return data;
}
-(void)check_xmlParserEnd
{
[indicator setHidden:YES];
}
- (void)connection:(CustomURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSMutableData *dataForConnection = [self dataForConnection:(CustomURLConnection*)connection];
[dataForConnection setLength:0];
}
- (void)connection:(CustomURLConnection *)connection didReceiveData:(NSData *)data {
NSMutableData *dataForConnection = [self dataForConnection:(CustomURLConnection*)connection];
[dataForConnection appendData:data];
}
-(void)connectionDidFinishLoading:(CustomURLConnection*)connection
{
NSMutableData *dataForConnection = [self dataForConnection:(CustomURLConnection*)connection];
[connection release];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSXMLParser *xmlParser = [[[NSXMLParser alloc] initWithData:dataForConnection] autorelease];
XMLParser *parser = [[XMLParser alloc] initXMLParser];
[xmlParser setDelegate:(id)parser];
parser.viewDelegate = (id)self;
[xmlParser parse ];
}
NSXMLParser is a synchronous parser. As soon as [xmlParser parse] returns , the parsing is done.
Since you use NSXMLParser and you set delegate as self, your class should implement NSXMLParserDelegate methods and the one "– parserDidEndDocument:" is called when all is finished.
Am working on an iPhone app,everything was going fine until I faced this crash, tiny_malloc_from_free_list. I am not sure why this crash is happening all of a sudden.Tried to google it but seems there aint enough suggestions to fix this one.
Please suggest any ideas how I can fix this problem.
Thanks,
Manoj
for reference here are some methods:
-(void) fetchProfileData
{
// Implemented ASIHTTP Request APIs
NSURL *url = [[NSURL URLWithString:SERVICE_NAME_PROFILEMANAGER] autorelease];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setValidatesSecureCertificate:NO];
[request setUsername:[[LoginManager sharedInstance] userName]];
[request setPassword:[[LoginManager sharedInstance] passWord]];
[request setDelegate:self];
[self.view addSubview:autheticateIndicator];
[autheticateIndicator startAnimating];
[authenticationLabel setHidden:NO];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSData *responseData = [request responseData];
NSString *theXml = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
[NSThread detachNewThreadSelector:#selector(parseXML:) toTarget:self withObject:theXml];
[autheticateIndicator stopAnimating];
[theXml release];
}
-(void) parseXML:(NSString *)xmlData
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[profilePersonnelNumber removeAllObjects];
// Load and parse the string data
tbxml = [[TBXML tbxmlWithXMLString:xmlData] retain];
// If TBXML found a root node, process element and iterate all children
if (tbxml.rootXMLElement) {
[self traverseElement:tbxml.rootXMLElement];
}
if ([profilePersonnelNumber count] > 0 ) {
NSDictionary *dict = [profilePersonnelNumber objectAtIndex:0];
if ([dict objectForKey:#"PersonnelNumber"])
{
[array release];
array = [[NSMutableArray arrayWithObjects:[dict valueForKey:#"PersonnelNumber"], nil] retain];
NSMutableString * result = [[NSMutableString alloc] init];
for (NSObject * obj in array)
{
[result appendString:[obj description]];
[[LoginManager sharedInstance] personnelNumber:[obj description]];
}
[result release];
}
}
[tbxml release];
[pool release];
//TODO: Uncomment this part, must required
if ([profilePersonnelNumber count] > 0) {
UITabBarController *controller = self.tabBarController;
[self presentModalViewController:controller animated:YES];
}
}
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.