iphone multiple image url loading in tableview - iphone

I want to display or load multiple images from a server and load it in tableview or image view ...if a single url with image is coming then imageview or tableview loads the image, but more that one image is coming then it did not load the multiple images,
my code is
NSString *urlVal = #"http://at.azinova.info/green4care/iphone/viewImage.php?id=";
NSString *urlVal1 = [urlVal stringByAppendingString:selectedCountryw];
NSURL *url1 = [NSURL URLWithString:urlVal1];
NSString *resultString = [NSString stringWithContentsOfURL:url1 encoding:NSUTF8StringEncoding error:nil];
resultString=[resultString stringByReplacingOccurrencesOfString:#"\n" withString:#""];
NSArray *profileedit = [resultString componentsSeparatedByString:#"#***#"];
lbl.text = resultString;
[web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:lbl.text]]];
timer = [NSTimer scheduledTimerWithTimeInterval:(1.0/2.0) target:self selector:#selector(tick) userInfo:nil repeats:YES];
UIAlertView *alert1 = [[UIAlertView alloc]initWithTitle:#"ALERT" message:resultString delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert1 show];
[alert1 release];
selectedCountryw is just an id
resultstring is the url from the server ,it may be one image or more than one image

You need to create a function that takes a parameter for selectedCountryw
The function returns a UIImage
Call the function every time you need an image, the function makes the request and creates the image
Set the image in the UITableView
Once you've gotten this far, let us know where you are and we'll jump right in and help.
-(UIImage*)getImage:(NSString*)country
{
NSString *urlString = [NSString stringWithFormat: #"http://at.azinova.info/green4care/iphone/viewImage.php?id=%#", country];
NSURL *url = [NSURL URLWithString: urlString];
NSString *strImage = [NSString stringWithContentsOfURL:url];
UIImage *image = [[UIImage imageWithData: [NSData dataWithContentsOfURL:[NSURL URLWithString:strImage]]] retain];
return image;
}
Better yet..Do a search on SO or Google for Lazy TableView Loading. That'll get you started.
Edited to provide additional information:
I'll leave it up to you to optimize.

Better option is the SDwebimage which is very simple to use and is the best library to do this kind of stuff here's the link to that

Related

iPhone how to validate a string is just a image name or image url in Objective - c?

On my xib I have a UITextField and UIImageView and a button,
what actually I want is when user can enter image name e.g. Default.png OR a full web URL of image and when press that button should check
if text is simple e.g. Default.png then use the local image and
if text is web URL with image then load data from image URL and create a image and then put on UIImageView.
I have checked many question here but did not get exact solution for what I want to achieve.
What I have done: (Which is not working)
// imageViewViewController.h
#import <UIKit/UIKit.h>
#interface imageViewViewController : UIViewController<UITextFieldDelegate>
{
IBOutlet UITextField * urlInput;
IBOutlet UIImageView * myImgView;
}
- (IBAction)submit:(id)sender;
#end
Code from .m file
- (IBAction)submit:(id)sender
{
NSString *url = urlInput.text;
UIImage *tempImg;
if([self validateUrl:url]) {
NSURL *imageurl = [NSURL URLWithString:url];
NSData *imagedata = [[NSData alloc]initWithContentsOfURL:imageurl];
tempImg = [UIImage imageWithData: imagedata];
} else {
tempImg = [UIImage imageNamed:url];
}
if(tempImg == nil){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Image not present!!!" message:#"Image not present!!!" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
} else {
myImgView.image = tempImg;
}
}
- (BOOL) validateUrl: (NSString *) candidate {
NSString *urlRegEx =
#"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";
NSPredicate *urlTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", urlRegEx];
return [urlTest evaluateWithObject:candidate];
}
Even after entering correct image URL it is showing me alert "Image not present!!!"
I think there is problem with my URL validation function.
You could use the
+(id)URLWithString:(NSString *)URLString
method of NSURL, which returns nil if the string is not URL
"The string with which to initialize the NSURL object. Must be a URL that conforms to RFC 2396. This method parses URLString according to RFCs 1738 and 1808." (c)
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/Reference/Reference.html
The code support the string is URL or Not,
NSString *incoming_string=#"http://www.gmail.com";
NSString *substring=#"http";
NSRange textRange = [incoming_string rangeOfString:substring];
if(textRange.location != NSNotFound){
NSLog(#"This is url image");
}else{
NSLog(#"This is SYSTEM Image");
}
UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:txtField.text]]];
if(img)
{
// Do something
}
Try this.
Use this method to check for a valid url
- (BOOL)isValidUrl:(NSString *)urlString{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
return [NSURLConnection canHandleRequest:request];
}
There are two alternative to check valid URL :
Method 1:
- (BOOL)CheckUrl:(NSString *)urlString {
NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
return [NSURLConnection canHandleRequest:request];
}
Method 2 :
NSString *urlRegEx = #"http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?";
Hope this might solve the problem
Use this code for check that its valid URL or not...
NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString: url]];
bool valid = [NSURLConnection canHandleRequest:req];

MBProgressHUD display Twitter

I have UIWebView which has loaded an image from the internet. I have a button which opens a UIActionSheet to give you the option to tweet this picture in the UIWebView. If you hit Tweet in the UIActionSheet it disappears and you see the UIWebview again. In the background the image is loading from the internet to attach it to the tweet. This may take several time depending of the imagesize.
I want to display now an information for the user that he knows what is going. I want to display a MBProgressHUD while the user is waiting that the Twitterconsole appears.
I try to start the HUD when the button is press and the UIActionSheet disappears but it didn't came up. It comes up in background when the Twitterconsole appears. This a little to late.
So what in the best place to start/stop the HUD?
Thanks
- (void) actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex{
if (buttonIndex == 0)
{
[self hudTweet];
[self tweet];
}
- (void) tweet {
if ([TWTweetComposeViewController canSendTweet])
{
TWTweetComposeViewController *tweetSheet =
[[TWTweetComposeViewController alloc] init];
[tweetSheet setInitialText:
#"Tweeting from "];
NSString *fullURL = beverageViewString;
NSURL *url = [NSURL URLWithString:fullURL];
NSString *paths = NSTemporaryDirectory();
NSError *error;
if (![[NSFileManager defaultManager] fileExistsAtPath:paths])
[[NSFileManager defaultManager] createDirectoryAtPath:paths withIntermediateDirectories:NO attributes:nil error:&error];
NSString *filePath = [paths stringByAppendingPathComponent:[self.title stringByAppendingFormat:#".jpeg"]];
NSData *jpegFile = [NSData dataWithContentsOfURL:url];
[jpegFile writeToFile:filePath atomically:YES];
[tweetSheet addImage:[UIImage imageWithContentsOfFile:filePath]];
[self presentModalViewController:tweetSheet animated:YES];
}
else
{
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Sorry"
message:#"You can't send a tweet right now because your account isn't configured"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
- (void) hudTweet {
HUD = [[MBProgressHUD alloc] initWithWindow:[UIApplication sharedApplication].keyWindow];
[self.view.window addSubview:HUD];
HUD.delegate = self;
HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
HUD.labelText = #"Loading";
HUD.detailsLabelText = #"updating data";
}
You are downloading your image in the main thread synchronously and thereby preventing the UI from updating. See this answer for a detailed explanation and possible workarounds.
The best option for you though, is to download the image asynchronously using something like NSURLRequest (see the showURL: example and according delegate callbacks).

Can we retrieve a particular method from json file and display it on UI ?

Hi everyone, I am new to iphone development..I am doing some application where I am stuck...I am having a textfield, button and a webview..
I am having a parsed json file..
I want to enter a string or method in the textfield, which is present in the JSON file..It should match with the method in json file and should display the contents of a method on webview..
I have done with button and a webview... I want to extend further with textfield and webview..
How can we do it? Please suggest me with example code...
//code
- (void)loadData
{
dataWebService = [[NSMutableData data] retain];
NSURLRequest *request = [[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://api.kivaws.org/v1/loans/search.json?status=fundraising"]]retain];
[[NSURLConnection alloc]initWithRequest:request delegate:self];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:dataWebService encoding:NSUTF8StringEncoding];
self.dataWebService = nil;
NSArray* latestLoans = [(NSDictionary*) [responseString JSONValue] objectForKey:#"loans"];
[responseString release];
NSDictionary* loan = [latestLoans objectAtIndex:0];
//fetch the data
NSNumber* fundedAmount = [loan objectForKey:#"funded_amount"];
NSNumber* loanAmount = [loan objectForKey:#"loan_amount"];
float outstandingAmount = [loanAmount floatValue] - [fundedAmount floatValue];
NSString* name = [loan objectForKey:#"name"];
NSString* country = [(NSDictionary*)[loan objectForKey:#"location"] objectForKey:#"country"];
//set the text to the label
label.numberOfLines = 0;
label.text = [NSString stringWithFormat:#"Latest loan: %# \n \n country: %# \n \n amount: $%.2f", name,country,outstandingAmount];
}
I think you are asking this: "How can I enter part of the URL in a textfield, and have it appended to a base URL and loaded into the webview?"
If so, you can do it quite easily. If your textfield is called "textfield" and webview called "webview" then do this:
NSString *baseUrl = #"http://whatever.com";
NSString *fullUrl = [baseUrl stringByAppendingString:textfield.text];
[webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:fullUrl]]];
Trigger it either with a button press or with UITextFieldDelegate's - (BOOL)textFieldShouldReturn:(UITextField *)textField
Edit:
You want to retrieve a value from the NSDictionary that the JSON generated based on a key you specify in the textfield. First, do
NSString *value = [dictionary objectForKey:textfield.text];
to get the value (assuming it is a string here). Then you want to display the value in a webview. You can either do it with loadHTMLString:baseURL: or with javascript via stringByEvaluatingJavaScriptFromString: (both methods of UIWebView). If you want to use loadHTMLString for example you can put in
NSString *html = [NSString stringWithFormat:#"<html><body>%#</body></html>", value];
[webview loadHTMLString:html baseURL:nil];

how to load image in background in UITableCell in iphone application

I have develop an RSS application. in My table cell I am displaying images which i retrive from imge link in RSS feed and Title.
Images are loaded successfully but the problem is that it hang my application.
as there any way to load image in background.
my current code is.
int blogEntryIndex1 = [indexPath indexAtPosition: [indexPath length] -1];
imgstring=[[blogEntries objectAtIndex: blogEntryIndex1] objectForKey: #"image"];
NSURL *url = [NSURL URLWithString:imgstring];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
cell.imageView.image=[img autorelease];
any idea please, Thanks in advance...
Repost... You should also look at lazy table loading via Apple's sample code http://developer.apple.com/iphone/library/samplecode/LazyTableImages/Introduction/Intro.html
Update another example here: http://www.markj.net/iphone-asynchronous-table-image/
Well guys i have done it the code is...
- (void) loadImage:(id)object {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Get the data to pass in
NSDictionary *dict = (NSDictionary *)object;
// Get the cell and the image string
NSString *imgstring = [dict objectForKey:#"imgstring"];
MyfirstCell *cell = [dict objectForKey:#"cell"];
NSURL *url = [NSURL URLWithString:imgstring];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
cell.myimnage.image = img;
[pool release];
}
I will call the above method in my code...
if(searching) {
//cell.textLabel.text = [copyListOfItems objectAtIndex:indexPath.row];
int blogEntryIndex = [indexPath indexAtPosition: [indexPath length] -1];
// Tell your code to load the image for a cell in the background
NSString *imgstring =[[blogEntries objectAtIndex: blogEntryIndex] objectForKey: #"image"];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:cell, #"cell", imgstring, #"imgstring", nil];
[self performSelectorInBackground:#selector(loadImage:) withObject:dict];
//background code end here..
Thanks to deanWombourne who has given me this code....
And take a look to this document also from Apple.
http://developer.apple.com/iphone/library/documentation/cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html
Most the time I use NSURLConnection to download things.
You can use this way:
((UIImageView *)cell.backgroundView).image = bgImage;
((UIImageView *)cell.selectedBackgroundView).image = bgImage;

Publish UIWebview via Facebook connect

I am using fbConnect in my Cocoa Touch application. I have UIWebview on my view, and I want to publish the UIWebview's context (its only text) to FaceBook.
How should I change the FBStream to publish my UIWebview?
FBStreamDialog* dialog2 = [[[FBStreamDialog alloc] init] autorelease];
dialog2.delegate = self;
dialog2.userMessagePrompt = #"Share Ghazals on your wall";
dialog2.attachment = #"{\"name\":\"Hafez Application for iPhone\","
"\"href\":\"http://itunes.apple.com/us/app/divan-of-hafez/id340865571?mt=8?tab=iphone\","
"\"media\":[{\"type\":\"image\","
"\"src\":\"http://photos-h.ak.fbcdn.net/photos-ak-sf2p/v43/67/279420942343/app_5_279420942343_8373.gif\","
"\"href\":\"http://developers.facebook.com/connect.php?tab=iphone/\"}],"
"\"properties\":{\"another link\":{\"text\":\"Hafez App HomePage\",\"href\":\"http://www.momeks.com/hafez\"}}}";
// replace this with a friend's UID
// dialog.targetId = #"999999";
[dialog2 show];
Here is my UIWebView Code:
NSString *path = [[NSBundle mainBundle] pathForResource:#"webViewContent" ofType:#"html"];
NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:path];
NSString *htmlString = [[NSString alloc] initWithData:
[readHandle readDataToEndOfFile] encoding:NSUTF8StringEncoding];
webView.opaque = NO;
webView.backgroundColor = [UIColor clearColor];
[self.webView loadHTMLString:htmlString baseURL:nil];
[htmlString release];
Not sure I understand what you mean by sharing UIWebview context.
If you want to publish text, then there are numerous examples for that on FBConnect.
You might want to try ShareKit, as it makes everything very easy....
If you could please re-explain the question, I could offer better help.
Godspeed,
Oded.