Is it possibile get thumbail image from .doc or .xls document? - iphone

I'm looking for create an image thumbnail from a MS doc/xls document's page,
but I found nothing about it.
For pdf documents I used Quarz framework, but I can't in this case.
Some help?

A web view can be used for making a MS doc preview.
I've tried once to do that with this piece of code.
It works ... but ... the web view need to work in graphical thread, so when this operation is running your interface is slower. Maybe can you optimized that.
Header
#interface WebViewThumbnailGenerationOperation: NSOperation <UIWebViewDelegate> {
BOOL finished;
}
#property(nonatomic,retain) NSURL* documentURL;
#property(nonatomic,retain) UIWebView* webView;
-(void)saveThumbnail:(UIImage*)thumbnail;
#end
Code
/**************************************************************************************************/
#pragma mark - WebViewBased Thumbnails
#implementation WebViewThumbnailGenerationOperation
#synthesize documentURL,webView;
-(void)dealloc {
RELEASE_SAFELY(documentURL);
[super dealloc];
}
- (void)loadWebView {
if (self.isCancelled) {
return;
}
self.webView = [[[UIWebView alloc] init] autorelease];
self.webView.delegate = self;
self.webView.scalesPageToFit = YES;
self.webView.frame = CGRectMake(0, 0, 290, 290);
NSURLRequest *request = [NSURLRequest requestWithURL:documentURL];
[self.webView loadRequest:request];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
if (self.isCancelled) {
return;
}
UIGraphicsBeginImageContext(CGSizeMake(290,290));
CGContextRef context = UIGraphicsGetCurrentContext();
[self.webView.layer renderInContext:context];
UIImage *thumbnail = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self performSelectorInBackground:#selector(saveThumbnail:) withObject:thumbnail];
self.webView = nil;
}
-(void)saveThumbnail:(UIImage*)thumbnail {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
if (self.isCancelled) {
return;
}
if(!thumbnail) {
return;
}
NSData* thumbnailData = UIImageJPEGRepresentation(thumbnail,0.8);
[IOHelper saveThumbnailData:thumbnailData forDocumentURL:documentURL];
[self willChangeValueForKey:#"isFinished"];
finished = YES;
[self didChangeValueForKey:#"isFinished"];
[pool release];
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
NSLog(#"Preview failed for %# error %#",document.name,error);
[self willChangeValueForKey:#"isFinished"];
finished = YES;
[self didChangeValueForKey:#"isFinished"];
self.webView = nil;
}
-(void)start {
finished = NO;
[super start];
}
- (void)main {
if (self.isCancelled) {
return;
}
[self performSelectorOnMainThread:#selector(loadWebView) withObject:nil waitUntilDone:YES];
}
-(BOOL)isFinished {
return finished;
}
#end
Edit: ARC version!
Header
#interface WebViewThumbnailGenerationOperation: NSOperation <UIWebViewDelegate>
#property(nonatomic, strong) NSURL* documentURL;
#property(nonatomic, strong) UIWebView* webView;
#property(nonatomic) BOOL finished;
-(void)saveThumbnail:(UIImage*)thumbnail;
#end
Code
/**************************************************************************************************/
#pragma mark - WebViewBased Thumbnails
#implementation WebViewThumbnailGenerationOperation
- (void)loadWebView {
if (self.isCancelled) {
return;
}
self.webView = [[UIWebView alloc] init];
self.webView.delegate = self;
self.webView.scalesPageToFit = YES;
self.webView.frame = CGRectMake(0, 0, 290, 290);
NSURLRequest *request = [NSURLRequest requestWithURL:documentURL];
[self.webView loadRequest:request];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
if (self.isCancelled) {
return;
}
UIGraphicsBeginImageContext(CGSizeMake(290,290));
CGContextRef context = UIGraphicsGetCurrentContext();
[self.webView.layer renderInContext:context];
UIImage *thumbnail = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self performSelectorInBackground:#selector(saveThumbnail:) withObject:thumbnail];
self.webView = nil;
}
-(void)saveThumbnail:(UIImage*)thumbnail {
#autoreleasepool {
if (self.isCancelled) {
return;
}
if(!thumbnail) {
return;
}
NSData* thumbnailData = UIImageJPEGRepresentation(thumbnail,0.8);
[IOHelper saveThumbnailData:thumbnailData forDocumentURL:documentURL];
[self willChangeValueForKey:#"isFinished"];
finished = YES;
[self didChangeValueForKey:#"isFinished"];
}
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
NSLog(#"Preview failed for %# error %#", document.name, error);
[self willChangeValueForKey:#"isFinished"];
finished = YES;
[self didChangeValueForKey:#"isFinished"];
self.webView = nil;
}
-(void)start {
finished = NO;
[super start];
}
- (void)main {
if (self.isCancelled) {
return;
}
[self performSelectorOnMainThread:#selector(loadWebView) withObject:nil waitUntilDone:YES];
}
-(BOOL)isFinished {
return finished;
}
#end

Related

Get file name and Data Type from ELCAlbumPickerController

I am working on ELCAlbumPickerController, i am able to select multiple images and upload, but in addition i want to get the file name and datatype of the file. how can i do that?
I am able to select either image or video , how can i select both image and video and any file at a time?
Please find my code below for your reference.
- (void)viewDidLoad {
UIImage *anImage = [UIImage imageNamed:#"elc-ios-icon.png"];
NSArray *Items = [NSArray arrayWithObjects:
#"A text line",
anImage, nil];
UIActivityViewController *ActivityView =
[[UIActivityViewController alloc]
initWithActivityItems:Items applicationActivities:nil];
[self presentViewController:ActivityView animated:YES completion:nil];
}
- (IBAction)launchController
{
ELCAlbumPickerController *albumController = [[ELCAlbumPickerController alloc] initWithNibName: nil bundle: nil];
ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initWithRootViewController:albumController];
[albumController setParent:elcPicker];
[elcPicker setDelegate:self];
ELCImagePickerDemoAppDelegate *app = (ELCImagePickerDemoAppDelegate *)[[UIApplication sharedApplication] delegate];
if ([app.viewController respondsToSelector:#selector(presentViewController:animated:completion:)]){
[app.viewController presentViewController:elcPicker animated:YES completion:nil];
} else {
[app.viewController presentModalViewController:elcPicker animated:YES];
}
[elcPicker release];
[albumController release];
}
- (IBAction)launchSpecialController
{
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
self.specialLibrary = library;
[library release];
NSMutableArray *groups = [NSMutableArray array];
[_specialLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if (group) {
[groups addObject:group];
} else {
// this is the end
[self displayPickerForGroup:[groups objectAtIndex:0]];
}
} failureBlock:^(NSError *error) {
self.chosenImages = nil;
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Error" message:[NSString stringWithFormat:#"Album Error: %# - %#", [error localizedDescription], [error localizedRecoverySuggestion]] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
NSLog(#"A problem occured %#", [error description]);
// an error here means that the asset groups were inaccessable.`
// Maybe the user or system preferences refused access.
}];
}
- (void)displayPickerForGroup:(ALAssetsGroup *)group
{
ELCAssetTablePicker *tablePicker = [[ELCAssetTablePicker alloc] initWithNibName: nil bundle: nil];
tablePicker.singleSelection = YES;
tablePicker.immediateReturn = YES;
ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initWithRootViewController:tablePicker];
elcPicker.delegate = self;
tablePicker.parent = elcPicker;
// Move me
tablePicker.assetGroup = group;
[tablePicker.assetGroup setAssetsFilter:[ALAssetsFilter allAssets]];
if ([self respondsToSelector:#selector(presentViewController:animated:completion:)]){
[self presentViewController:elcPicker animated:YES completion:nil];
} else {
[self presentModalViewController:elcPicker animated:YES];
}
[tablePicker release];
[elcPicker release];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
return YES;
} else {
return toInterfaceOrientation != UIInterfaceOrientationPortraitUpsideDown;
}
}
#pragma mark ELCImagePickerControllerDelegate Methods
- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
if ([self respondsToSelector:#selector(dismissViewControllerAnimated:completion:)]){
[self dismissViewControllerAnimated:YES completion:nil];
} else {
[self dismissModalViewControllerAnimated:YES];
}
for (UIView *v in [_scrollView subviews]) {
[v removeFromSuperview];
}
CGRect workingFrame = _scrollView.frame;
workingFrame.origin.x = 0;
images = [NSMutableArray arrayWithCapacity:[info count]];
for(NSDictionary *dict in info) {
UIImage *image = [dict objectForKey:UIImagePickerControllerOriginalImage];
[images addObject:image];
UIImageView *imageview = [[UIImageView alloc] initWithImage:image];
[imageview setContentMode:UIViewContentModeScaleAspectFit];
imageview.frame = workingFrame;
[_scrollView addSubview:imageview];
[imageview release];
workingFrame.origin.x = workingFrame.origin.x + workingFrame.size.width;
}
self.chosenImages = images;
NSLog(#"Images:%#",images);
[_scrollView setPagingEnabled:YES];
[_scrollView setContentSize:CGSizeMake(workingFrame.origin.x, workingFrame.size.height)];
for (int i=0; i< images.count; i++) {
NSData *image = UIImageJPEGRepresentation(images[i], 0.1);
NSLog(#"NSDATA:%#",image);
NSMutableString *urlString = [[NSMutableString alloc] initWithFormat:#"name=thefile&&filename=recording"];
[urlString appendFormat:#"%#", image];
NSLog(#"urlstring:%#",urlString);
NSData *postData = [urlString dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSString * namecount=[NSString stringWithFormat:#"fn%i.png",i];
NSString * baseurl =[[NSString alloc]initWithFormat:#"http://199.198.12.555/serviceService.svc/serviceupload?fileName=%#",namecount];
NSURL *url = [NSURL URLWithString:baseurl];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod: #"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded"
forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBody:image];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
[connection start];
}
NSLog(#"%#",images[0]);
NSLog(#"%lu",(unsigned long)images.count);
}
-(IBAction)upload:(id)sender{
}
- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker
{
if ([self respondsToSelector:#selector(dismissViewControllerAnimated:completion:)]){
[self dismissViewControllerAnimated:YES completion:nil];
} else {
[self dismissModalViewControllerAnimated:YES];
}
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload
{
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc
{
[_specialLibrary release];
[_scrollView release];
[super dealloc];
}
#end
#implementation APActivityProvider
- (id) activityViewController:(UIActivityViewController *)activityViewController
itemForActivityType:(NSString *)activityType
{
if ( [activityType isEqualToString:UIActivityTypePostToTwitter] )
return #"This is a #twitter post!";
if ( [activityType isEqualToString:UIActivityTypePostToFacebook] )
return #"This is a facebook post!";
if ( [activityType isEqualToString:UIActivityTypeMessage] )
return #"SMS message text";
if ( [activityType isEqualToString:UIActivityTypeMail] )
return #"Email text here!";
if ( [activityType isEqualToString:#"it.albertopasca.myApp"] )
return #"OpenMyapp custom text";
return nil;
}
- (id) activityViewControllerPlaceholderItem:(UIActivityViewController *)activityViewController { return #""; }
#end
#implementation APActivityIcon
- (NSString *)activityType { return #"it.albertopasca.myApp"; }
- (NSString *)activityTitle { return #"Open Maps"; }
- (UIImage *) activityImage { return [UIImage imageNamed:#"elc-ios-icon.png"]; }
- (BOOL) canPerformWithActivityItems:(NSArray *)activityItems { return YES; }
- (void) prepareWithActivityItems:(NSArray *)activityItems { }
- (UIViewController *) activityViewController { return nil; }
- (void) performActivity {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"maps://"]];
}
#end
Thanks
You can get the asset URL using the key UIImagePickerControllerReferenceURL which would give the 'name', but that probably won't be very useful as its probably a UUID. The UIImagePickerControllerMediaType key contains the type.

Can i load images from the device's documents directory to AsyncImageView?

Actually, I am not sure about this but i have this condition where i check whether internet is available or not and accordingly load the image into AsyncImageView. It works fine when i load any image from the internet, but is it possible to load a local image to AsyncImageView?
I guess you mean AsyncImageView by Nick Lockwood? This is simply a category to UIImageView, so when you have the image already, why not set the image property directly?
Actually i got the solution to this problem.All i did was this
NSURL *theURL = [NSURL fileURLWithPath:#"/Users/gaurav/Library/Application Support/iPhone Simulator/5.0/Applications/AC6E9B2E-DB25-4933-A338-755B134E1A61/Documents/Attachment290_294_1344928691.jpeg"];
NSLog(#"local URl is::%#",theURL);
[self.asyncimageview loadImageFromURL:theURL];
Perhaps the following will help you.
Make a new file
Inherit from UIImageView
Copy/Paste the following code.
import
import "ASIHTTPRequest.h"
#interface AsynchronousImageView : UIImageView{
NSMutableData *data;
UIActivityIndicatorView *activityIndicator;
NSString *urlString; // key for image cache dictionary
ASIHTTPRequest *requestLocal;
}
#property(nonatomic,assign) UIActivityIndicatorView *activityIndicator;
(void)loadImageFromURLString:(NSString *)theUrlString;
(void)loadImageFromNSURL:(NSURL *)theUrl;
(void)loadImageFromFile:(NSString *)filePath;
-(void) showLoader;
-(void) stopLoader;
#end
Then In .m file paste the following.
import "AsynchronousImageView.h"
import "ASIDownloadCache.h"
#implementation AsynchronousImageView
#synthesize activityIndicator;
(id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
//[self setContentMode:UIViewContentModeScaleAspectFit];
}
return self;
}
-(void)dealloc
{
if (requestLocal) {
[requestLocal setDelegate:nil];
}
requestLocal = nil;
activityIndicator = nil;
[super dealloc];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
(void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
-(void) showLoader{
if(activityIndicator == nil){
activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
[self addSubview:activityIndicator];
activityIndicator.frame = CGRectMake(self.bounds.size.width / 2.0f - activityIndicator.frame.size.width /2.0f, self.bounds.size.height / 2.0f - activityIndicator.frame.size.height /2.0f, activityIndicator.frame.size.width, activityIndicator.frame.size.height);
[activityIndicator release];
}
[activityIndicator startAnimating];
}
-(void) stopLoader{
if(activityIndicator){
[activityIndicator stopAnimating];
[activityIndicator removeFromSuperview];
activityIndicator = nil;
}
}
(void)loadImageFromFile:(NSString *)filePath {
UIImage *img = [UIImage imageWithContentsOfFile:filePath];
[self setImage:img];
[self stopLoader];
}
(void)loadImageFromURLString:(NSString *)theUrlString
{
/if (requestLocal) {
[requestLocal setDelegate:nil];
}/
requestLocal = nil;
[self showLoader];
NSURL *url = [NSURL URLWithString:theUrlString];
requestLocal = [ASIHTTPRequest requestWithURL:url];
[requestLocal setDelegate:self];
[requestLocal setDidFailSelector:#selector(requestFailed)];
[requestLocal setDownloadCache:[ASIDownloadCache sharedCache]];
[requestLocal setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
[requestLocal startAsynchronous];
self.image = [UIImage imageNamed:#"playerDefault.png"];
}
-(void)loadImageFromNSURL:(NSURL *)theUrl
{
if (requestLocal) {
[requestLocal setDelegate:nil];
}
requestLocal = nil;
requestLocal = [ASIHTTPRequest requestWithURL:theUrl];
[requestLocal setDelegate:self];
[requestLocal setDidFailSelector:#selector(requestFailed)];
[requestLocal startAsynchronous];
}
(void)requestFinished:(ASIHTTPRequest *)request
{
requestLocal = nil;
[self stopLoader];
UIImage *tempArt = [UIImage imageWithData:[request responseData]];
if (tempArt) {
self.image = tempArt;
}
[data release];
data = nil;
}
-(void)requestFailed:(ASIHTTPRequest *)request{
requestLocal = nil;
[self stopLoader];
[data release];
data = nil;
}
#end
Then in your ViewComtroller .h import AsycnhronousImageView class and write this
Make the IBOutlet of your image like this.
IBOutlet AsycnhronousImageView *image;
Change the class in xib AsycnhronousImageView rather than UIImage View
Call the following Method
(void)loadImageFromFile:(NSString *)filePath;

iOS NSURLConnection memory leak

i got code like this
#import "UIWebImageView.h"
#interface UIWebImageView (hiddenMethods)
- (void) initDefaults;
#end
#implementation UIWebImageView (hiddenMethods)
- (void) initDefaults
{
self.showActivityIndicator = NO;
self.activityIndicatorStyle = UIActivityIndicatorViewStyleWhite;
self.activityIndicatorSize = CGSizeMake(20.0, 20.0);
//data = [[NSMutableData alloc] init];
}
#end
#implementation UIWebImageView
#synthesize showActivityIndicator;
#synthesize activityIndicatorStyle;
#synthesize activityIndicatorSize;
- (id) init
{
if (self = [super init])
{
[self initDefaults];
}
return self;
}
- (void) loadFromURL:(NSString *) url
{
[self.image release];
self.image = nil;
request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30.0];
if (connection == nil)
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
// activity indicator start
indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:activityIndicatorStyle];
indicator.frame = CGRectMake((self.frame.size.width - activityIndicatorSize.width)/2, (self.frame.size.height - activityIndicatorSize.height)/2,
activityIndicatorSize.width, activityIndicatorSize.height);
[self addSubview:indicator];
[indicator startAnimating];
}
- (void) dealloc
{
[data release];
[indicator release];
[connection release];
[super dealloc];
}
#pragma mark -
#pragma mark connection delegate
- (void) connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData
{
if (data == nil)
data = [[NSMutableData alloc] initWithCapacity:2048];
[data appendData:incrementalData];
}
- (void) connectionDidFinishLoading:(NSURLConnection *)theConnection
{
self.image = [UIImage imageWithData:data];
[indicator removeFromSuperview];
//data = nil;
[data release], data = nil;
[connection release], connection = nil;
[indicator release], indicator = nil;
}
- (void) connection:(NSURLConnection *)theConnection didFailWithError:(NSError *)error
{
self.image = [UIImage imageNamed:#"icon.jpg"];
[indicator removeFromSuperview];
//data = nil;
[data release], data = nil;
[connection release], connection = nil;
[indicator release], indicator = nil;
}
I'm using this for downloading images from web. one image for every cell in in table. and it works fine when image is not going out of the screen. BUT when u scrolling tableView fast and some images did not finished loading while they are on screen there huge memory leaks.
i know where is the leak and why its leaking. but i can't find solution.
any thoughts ?
thank you
PS sorry for my english
UPDATE
here is a code for adding images into tableView
UIWebImageView *tmpImageView = [[UIWebImageView alloc] initWithFrame:CGRectMake(0, 0, 57, 76)];
tmpImageView.showActivityIndicator = YES;
tmpImageView.contentMode = UIViewContentModeScaleAspectFit;
tmpImageView.activityIndicatorStyle = UIActivityIndicatorViewStyleGray;
[tmpImageView loadFromURL:[[tableArray objectAtIndex:indexPath.row] objectForKey:#"picurl"]];
[cell addSubview:tmpImageView];
[tmpImageView release];
and I'm repeating = ) its leaking only when it not finished loading and went off the screen while scrolling
The leaks are happening due to the allocation of UIWebImageView objects recursively (considering you are using reusable cells).
you should change your code to:
UIWebImageView *tmpImageView = [cell viewWithTag:2011];
if(!tmpImageView)
{
tmpImageView = [[UIWebImageView alloc] initWithFrame:CGRectMake(0, 0, 57, 76)];
tmpImageView.showActivityIndicator = YES;
tmpImageView.tag = 2011;
tmpImageView.contentMode = UIViewContentModeScaleAspectFit;
tmpImageView.activityIndicatorStyle = UIActivityIndicatorViewStyleGray;
[cell addSubview:tmpImageView];
[tmpImageView release];
}
[tmpImageView loadFromURL:[[tableArray objectAtIndex:indexPath.row] objectForKey:#"picurl"]];
you have to handle for the showActivityIndicator thing some how...based upon your code but the above mentioned change will remove your memory leaks.
Autorelase your NSURLConnection with this syntax
connection = [NSURLConnection connectionWithRequest:request delegate:self];
and delete your [connection release], connection = nil;

UIActivityIndicatorView not working on programmatically UIWebView in mySubView

My myViewController.h contains:
#import <UIKit/UIKit.h>
#interface myViewController : UIViewController {
UIScrollView *myScrollView;
UIView *mySubView;
UIWebView *myWebView;
UIActivityIndicatorView *myIndicator;
}
#property (nonatomic, retain) IBOutlet UIScrollView *myScrollView;
#end
My myViewController.m contains:
#import "myViewController.h"
#implementation myViewController
#synthesize myScrollView;
...
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *bgColors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor greenColor], [UIColor blueColor], nil];
for (int i = 0; i < bgColors.count; i++)
{
CGRect frameNew;
frameNew.origin.x = self.myScrollView.frame.size.width * i;
frameNew.origin.y = 0;
frameNew.size = self.myScrollView.frame.size;
mySubView = [[UIView alloc] initWithFrame:frameNew];
mySubView.backgroundColor = [bgColors objectAtIndex:i];
[self.myScrollView addSubview:mySubView];
myIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
myIndicator.center = CGPointMake(160, 100);
myIndicator.hidesWhenStopped = NO;
CGRect webFrame = CGRectMake(self.myScrollView.frame.size.width * i, 0, 320, 320);
myWebView = [[UIWebView alloc] initWithFrame:webFrame];
[myWebView setDelegate:(id)self];
[myWebView addSubview:myIndicator];
NSString *urlAddress = #"http://www.google.com/";
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[myWebView loadRequest:requestObj];
[self.myScrollView addSubview:myWebView];
[myIndicator release];
[myWebView release];
[mySubView release];
}
self.myScrollView.contentSize = CGSizeMake(self.myScrollView.frame.size.width * bgColors.count, self.myScrollView.frame.size.height);
}
-(void)webViewDidStartLoad: (UIWebView *)webView
{
NSLog(#"Web view did start loading");
[myIndicator startAnimating];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
-(void)webViewDidFinishLoad: (UIWebView *)webView
{
NSLog(#"Web view did finish loading");
[myIndicator stopAnimating];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
[myIndicator stopAnimating];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSString* errorString = [NSString stringWithFormat:#"<html>%#</html>", error.localizedDescription];
[myWebView loadHTMLString:errorString baseURL:nil];
}
...
Load indicator does not work on the first two mySubView in myWebView, works only on the last mySubView in myWebView.
In the first two mySubView in myWebView, myIndicator displayed but not active.
Tell me what's wrong doing?
That is because myIndicator is pointing to the last activity indicator view. All previous references are lost. Luckily, since it is a subview of the web view, we can get a reference to it. This should help –
-(void)webViewDidStartLoad: (UIWebView *)webView
{
UIActivityIndicatorView *actView;
for ( id object in webView.subviews ) {
if ([object isMemberOfClass:[UIActivityIndicatorView class]]) {
actView = (UIActivityIndicatorView*)object;
}
}
NSLog(#"Web view did start loading");
[actView startAnimating];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
-(void)webViewDidFinishLoad: (UIWebView *)webView
{
UIActivityIndicatorView *actView;
for ( id object in webView.subviews ) {
if ([object isMemberOfClass:[UIActivityIndicatorView class]]) {
actView = (UIActivityIndicatorView*)object;
}
}
NSLog(#"Web view did finish loading");
[actView stopAnimating];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
UIActivityIndicatorView *actView;
for ( id object in webView.subviews ) {
if ([object isMemberOfClass:[UIActivityIndicatorView class]]) {
actView = (UIActivityIndicatorView*)object;
}
}
[actView stopAnimating];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSString* errorString = [NSString stringWithFormat:#"<html>%#</html>", error.localizedDescription];
[myWebView loadHTMLString:errorString baseURL:nil];
}

how can i integrate ticker in iphone application

i want to run my view based window application with ticker.i have code for ticker but it is in cocoa..
so how can i integrate cocoa application in my project.?
this is TickerView.h file
#import <Cocoa/Cocoa.h>
#interface TickerView : NSTextView {
#private
NSTimer *mTimer;
double mOffset;
}
- (NSString *)stringValue;
- (void)setStringValue:(NSString *)stringValue;
- (void)appendString:(NSString *)s;
- (IBAction)startAnimation:(id)sender;
- (IBAction)stopAnimation:(id)sender;
#end
This is TickerView.m file
#import "TickerView.h"
#implementation TickerView
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self setEditable:NO];
NSTextContainer *container = [self textContainer];
[container setWidthTracksTextView:NO];
[container setContainerSize:NSMakeSize(99999., frame.size.height)];
}
return self;
}
- (void)dealloc {
[self stopAnimation:self];
[super dealloc];
}
- (void)drawRect:(NSRect)rect {
[super drawRect:rect];
}
- (NSString *)stringValue {
return [[self textStorage] string];
}
- (NSDictionary *)standardAttributes {
return [NSDictionary dictionaryWithObjectsAndKeys:
[NSFont fontWithName:#"Helvetica" size:([self frame].size.height * 0.8)], NSFontAttributeName,
[NSColor redColor], NSForegroundColorAttributeName,
nil];
}
- (void)setStringValue:(NSString *)s {
NSRange fullRange = NSMakeRange(0, [[self textStorage] length]);
NSAttributedString *sa = [[[NSAttributedString alloc]initWithString:s attributes:[self standardAttributes]] autorelease];
[[self textStorage] replaceCharactersInRange:fullRange withAttributedString:sa];
}
- (void)appendString:(NSString *)s {
NSRange endRange = NSMakeRange([[self textStorage] length], 0);
NSAttributedString *sa = [[[NSAttributedString alloc]initWithString:s attributes:[self standardAttributes]] autorelease];
[[self textStorage] replaceCharactersInRange:endRange withAttributedString:sa];
}
- (IBAction)startAnimation:(id)sender {
if (nil == mTimer) {
mTimer = [NSTimer scheduledTimerWithTimeInterval:1./60. target:self selector:#selector(step:) userInfo:nil repeats:YES];
}
}
- (IBAction)stopAnimation:(id)sender {
if (mTimer) {
[mTimer invalidate];
[mTimer release];
mTimer = nil;
}
}
- (void)step:(NSTimer *)timer {
mOffset -= 2; // pixels per tick
[self setTextContainerInset:NSMakeSize(mOffset, 0)];
[self setNeedsDisplay:YES];
}
#end
You can't just drop it in (as far as I know).
I'd do it by changing your inheritance from NSTextView to UILabel and reading the docs for that. then just work through the code bit by bit until it works ;)