how can i integrate ticker in iphone application - iphone

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 ;)

Related

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

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

AlAssetsLibrary issue, code works in 4.3 but not 5.0

Here's my issue, if I access this class with iOS 4.X, the code works fine.... however whenever I try to access it with iOS 5.0, I get nil values for the groups & assets. What's the best way to get this to work? I'm posting the entire class for a reference...
.h
#import <UIKit/UIKit.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "DejViewController.h"
#class Event, Venue;
#interface SelectMediaViewController : DejViewController <UITableViewDelegate, UITableViewDataSource> {
Event *event;
Venue *venue;
UITableView *tableView;
NSMutableArray *selectedAssets;
NSMutableArray *allMedia;
ALAssetsLibrary *library;
NSMutableArray *assetGroups;
}
#property (nonatomic, retain) Event *event;
#property (nonatomic, retain) Venue *venue;
#property (nonatomic, retain) IBOutlet UITableView *tableView;
#property (nonatomic, retain) NSMutableArray *allMedia;
#property (nonatomic, retain) NSMutableArray *assetGroups;
- (IBAction)continuePressed:(id)sender;
#end
.m
#import <ImageIO/ImageIO.h>
#import "SelectMediaViewController.h"
#import "CaptionAllMediaViewController.h"
#import "MediaItem.h"
#import "CLValueButton.h"
#import "SelectMediaTableViewCell.h"
#define kMediaGridSize 75
#define kMediaGridPadding 4
#define kSelectImageTag 828
#interface SelectMediaViewController(Private)
- (void)setContentForButton:(CLValueButton *)button withAsset:(ALAsset *)asset;
- (void)loadData;
#end
#implementation SelectMediaViewController
#synthesize event, venue;
#synthesize tableView;
#synthesize allMedia,assetGroups;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
selectedAssets = [[NSMutableArray alloc] init];
showNextButton = YES;
}
return self;
}
- (void)dealloc {
[tableView release];
[event release];
[venue release];
[library release];
[allMedia release];
[selectedAssets release];
[assetGroups release];
[super dealloc];
}
- (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.
}
#pragma mark - View lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"SelectMediaViewController - viewDidLoad");
}
- (void)viewDidUnload {
NSLog(#"SelectMediaViewController - viewDidUnload");
[self setTableView:nil];
[super viewDidUnload];
}
- (void)viewDidAppear:(BOOL)animated {
NSLog(#"SelectMediaViewController - viewDidAppear");
[super viewDidAppear:animated];
[self setNavTitle:#"Select Media"];
[self loadData];
[self.tableView reloadData];
float contentOffset = self.tableView.contentSize.height - self.tableView.frame.size.height;
if (contentOffset < 0) contentOffset = 0;
[self.tableView setContentOffset:CGPointMake(0, contentOffset) animated:NO];
}
- (void)viewDidDisappear:(BOOL)animated {
NSLog(#"SelectMediaViewController - viewDidDisappear");
self.allMedia = nil;
[selectedAssets removeAllObjects];
[self.tableView reloadData];
}
- (void)loadData {
NSMutableArray *tempArray = [[NSMutableArray array] init];
library = [[ALAssetsLibrary alloc] init];
void (^assetEnumerator)(ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
if(result != NULL) {
NSLog(#"See Asset: %#", result);
[tempArray addObject:result];
NSLog(#"assets count: %i", tempArray.count);
}
else {
NSLog(#"result nil or end of list");
}
};
void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop) {
if(group != nil) {
[group enumerateAssetsUsingBlock:assetEnumerator];
NSLog(#"group: %#",group);
}
else {
NSLog(#"group nil or end of list");
}
if (stop) {
self.allMedia = [NSMutableArray arrayWithCapacity:[tempArray count]];
self.allMedia = tempArray;
NSLog(#"Loaded data: %d & %d", [tempArray count], [self.allMedia count]);
}
};
//ALAssetsLibrary *library = [[[ALAssetsLibrary alloc] init] autorelease];
[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
usingBlock:assetGroupEnumerator
failureBlock:^(NSError *error) {
}];
//[library release];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (IBAction)continuePressed:(id)sender {
if ([selectedAssets count] > 0) {
CaptionAllMediaViewController *captionVC = [[CaptionAllMediaViewController alloc] initWithNibName:nil bundle:nil];
captionVC.event = self.event;
captionVC.venue = self.venue;
// Create media items
NSMutableArray *mediaItems = [NSMutableArray arrayWithCapacity:[selectedAssets count]];
for (ALAsset *asset in selectedAssets) {
MediaItem *item = [[MediaItem alloc] init];
item.asset = asset;
NSDictionary *metadata = [[asset defaultRepresentation] metadata];
NSDictionary *gpsMeta = [metadata objectForKey:#"{GPS}"];
if (gpsMeta) {
float latitude = [[gpsMeta objectForKey:#"Latitude"] floatValue];
if ([[gpsMeta objectForKey:#"LatitudeRef"] isEqualToString:#"S"]) latitude = latitude * -1;
float longitude = [[gpsMeta objectForKey:#"Longitude"] floatValue];
if ([[gpsMeta objectForKey:#"LongitudeRef"] isEqualToString:#"W"]) longitude = longitude * -1;
item.location = CLLocationCoordinate2DMake(latitude, longitude);
}
[mediaItems addObject:item];
[item release];
}
captionVC.media = mediaItems;
[self.navigationController pushViewController:captionVC animated:YES];
[captionVC release];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Images Selected"
message:#"Please select at least one image to continue."
delegate:nil
cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
}
- (void)imagePressed:(CLValueButton *)sender {
BOOL currentlySelected = [selectedAssets containsObject:sender.valueObject];
UIImageView *imageView = (UIImageView *)[sender viewWithTag:kSelectImageTag];
if (!currentlySelected) {
[imageView setImage:[UIImage imageNamed:#"image-select-active.png"]];
[selectedAssets addObject:sender.valueObject];
} else {
[imageView setImage:[UIImage imageNamed:#"image-select.png"]];
[selectedAssets removeObject:sender.valueObject];
}
}
#pragma Table view methods
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(#"Getting table view count: %d", [self.allMedia count]);
if ([self.allMedia count] == 0) return 0;
return ceil([self.allMedia count] / 4.0);
}
- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 83;
NSLog(#"return83");
}
- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
SelectMediaTableViewCell *cell = (SelectMediaTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:#"MEDIA_CELL"];
if (!cell) {
cell = [[[NSBundle mainBundle] loadNibNamed:#"SelectMediaTableViewCell" owner:nil options:nil] objectAtIndex:0];
// wire up selectors
[cell.image1 addTarget:self action:#selector(imagePressed:) forControlEvents:UIControlEventTouchUpInside];
[cell.image2 addTarget:self action:#selector(imagePressed:) forControlEvents:UIControlEventTouchUpInside];
[cell.image3 addTarget:self action:#selector(imagePressed:) forControlEvents:UIControlEventTouchUpInside];
[cell.image4 addTarget:self action:#selector(imagePressed:) forControlEvents:UIControlEventTouchUpInside];
}
int startIndex = indexPath.row * 4;
for (int i = 0; i < 4; i++) {
ALAsset *thisAsset = (startIndex + i) < [self.allMedia count] ? [self.allMedia objectAtIndex:startIndex + i] : nil;
CLValueButton *button = nil;
switch (i) {
case 0:
button = cell.image1;
break;
case 1:
button = cell.image2;
break;
case 2:
button = cell.image3;
break;
case 3:
button = cell.image4;
break;
default:
break;
}
[self setContentForButton:button withAsset:thisAsset];
UIImageView *imageView = (UIImageView *)[button viewWithTag:kSelectImageTag];
// letse see if it's selected or not...
if ([selectedAssets containsObject:button.valueObject]) {
[imageView setImage:[UIImage imageNamed:#"image-select-active.png"]];
} else {
[imageView setImage:[UIImage imageNamed:#"image-select.png"]];
}
}
return cell;
}
- (void)setContentForButton:(CLValueButton *)button withAsset:(ALAsset *)asset {
button.hidden = asset == nil;
if (asset) {
CGImageRef image = [asset thumbnail];
[button setImage:[UIImage imageWithCGImage:image] forState:UIControlStateNormal];
}
[button setValueObject:asset];
}
#pragma -
#end
Any help would be much appreciated, I've been trying to figure this out for 3 days...
The ALAssetsLibrary page in the online documentation now says "The lifetimes of objects you get back from a library instance are tied to the lifetime of the library instance."

Posting Score to FB using FBConnect

Hi all
Just wondering how I modify my code to post a score to Facebook
Currently all working with the following posting to facebook, just no score
#import "GameOverViewController.h"
#import "SoundEffects.h"
#import "FBConnect.h"
#implementation GameOverViewController
#synthesize scoreLabel, highScore;
#synthesize session = _session;
#synthesize postScoreButton = _postScoreButton;
#synthesize logoutButton = _logoutButton;
#synthesize loginDialog = _loginDialog;
#synthesize facebookName = _facebookName;
#synthesize posting = _posting;
- (void)viewDidLoad {
[super viewDidLoad];
NSString *gameOverPath = [[NSBundle mainBundle] pathForResource:#"gameover" ofType:#"png"];
UIImage *gameOver = [[UIImage alloc] initWithContentsOfFile: gameOverPath];
UIImageView *gameOverViewTemp = [[UIImageView alloc] initWithImage:gameOver];
[self.view addSubview:gameOverViewTemp];
gameOverText = [SpriteHelpers setupAnimatedSprite:self.view numFrames:3 withFilePrefix:#"gameovertext" withDuration:0.4 ofType:#"png" withValue:0];
gameOverText.center = CGPointMake(160, 90);
scoreLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 200, 320, 70)];
scoreLabel.text = [NSString stringWithFormat:#"%d points", highScore];
[self.view addSubview:scoreLabel];
scoreLabel.textColor = [UIColor whiteColor];
scoreLabel.backgroundColor = [UIColor clearColor];
scoreLabel.font = [UIFont boldSystemFontOfSize:42];
scoreLabel.textAlignment = UITextAlignmentCenter;
[gameOverViewTemp release];
[gameOver release];
// Set these values from your application page on http://www.facebook.com/developers
// Keep in mind that this method is not as secure as using the sessionForApplication:getSessionProxy:delegate method!
// These values are from a dummy facebook app I made called MyGrades - feel free to play around!
static NSString* kApiKey = #"2af22b07c9730d3d502a7a401b9e48d7";
static NSString* kApiSecret = #"738116a372130f659a761078de08b3d4";
_session = [[FBSession sessionForApplication:kApiKey secret:kApiSecret delegate:self] retain];
// Load a previous session from disk if available. Note this will call session:didLogin if a valid session exists.
[_session resume];
[super viewDidLoad];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[self.view removeFromSuperview];
[self release];
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (IBAction)postScoreTapped:(id)sender {
_posting = YES;
// If we're not logged in, log in first...
if (![_session isConnected]) {
self.loginDialog = nil;
_loginDialog = [[FBLoginDialog alloc] init];
[_loginDialog show];
}
// If we have a session and a name, post to the wall!
else if (_facebookName != nil) {
[self postToWall];
}
// Otherwise, we don't have a name yet, just wait for that to come through.
}
- (IBAction)logoutButtonTapped:(id)sender {
[_session logout];
}
#pragma mark FBSessionDelegate methods
- (void)session:(FBSession*)session didLogin:(FBUID)uid {
[self getFacebookName];
}
- (void)session:(FBSession*)session willLogout:(FBUID)uid {
_logoutButton.hidden = YES;
_facebookName = nil;
}
#pragma mark Get Facebook Name Helper
- (void)getFacebookName {
NSString* fql = [NSString stringWithFormat:
#"select uid,name from user where uid == %lld", _session.uid];
NSDictionary* params = [NSDictionary dictionaryWithObject:fql forKey:#"query"];
[[FBRequest requestWithDelegate:self] call:#"facebook.fql.query" params:params];
}
#pragma mark FBRequestDelegate methods
- (void)request:(FBRequest*)request didLoad:(id)result {
if ([request.method isEqualToString:#"facebook.fql.query"]) {
NSArray* users = result;
NSDictionary* user = [users objectAtIndex:0];
NSString* name = [user objectForKey:#"name"];
self.facebookName = name;
_logoutButton.hidden = NO;
[_logoutButton setTitle:[NSString stringWithFormat:#"Facebook: Logout as %#", name] forState:UIControlStateNormal];
if (_posting) {
[self postToWall];
_posting = NO;
}
}
}
#pragma mark Post to Wall Helper
- (void)postToWall {
FBStreamDialog* dialog = [[[FBStreamDialog alloc] init] autorelease];
dialog.userMessagePrompt = #"Enter your message:";
dialog.attachment = [NSString stringWithFormat:#"{\"name\":\"%# just played SpaceRide on the iPhone!\",\"href\":\"http://www.spaceride.me/\",\"caption\":\"%# must be really skillful!\",\"description\":\"\",\"media\":[{\"type\":\"image\",\"src\":\"http://www.spaceride.me/fbicon.png\",\"href\":\"http://www.spaceride.me/\"}]}",
_facebookName, _facebookName];
dialog.actionLinks = #"[{\"text\":\"Get SpaceRide!\",\"href\":\"http://www.spaceride.me/\"}]";
[dialog show];
}
- (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 {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[scoreLabel release];
[super dealloc];
}
#end
Change:
dialog.attachment = [NSString stringWithFormat:#"{\"name\":\"%# just played SpaceRide on the iPhone!\",\"href\":\"http://www.spaceride.me/\",\"caption\":\"%# must be really skillful!\",\"description\":\"\",\"media\":[{\"type\":\"image\",\"src\":\"http://www.spaceride.me/fbicon.png\",\"href\":\"http://www.spaceride.me/\"}]}",
_facebookName, _facebookName];
To something like:
dialog.attachment = [NSString stringWithFormat:#"{\"name\":\"%# just got %d playing SpaceRide on the iPhone!\",\"href\":\"http://www.spaceride.me/\",\"caption\":\"%# must be really skillful!\",\"description\":\"\",\"media\":[{\"type\":\"image\",\"src\":\"http://www.spaceride.me/fbicon.png\",\"href\":\"http://www.spaceride.me/\"}]}",
_facebookName, score, _facebookName];
Change 'score' to the name of your integer score variable.

Three20 to save images?(Close)

i'm a new iPhone application developer,i need create one application like photo gallery.Now my problem is i donno how to save a image to photo album.
i have build my project is no error no werning to me.in my simulator can run the project.
But i cnt see any things i add.Hope can help me.Thanks.
my code here.
Three20PhotoDemoAppDelegate.h
#import <UIKit/UIKit.h>
#interface Three20PhotoDemoAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#end
Three20PhotoDemoAppDelegate.m
#import "Three20PhotoDemoAppDelegate.h"
#import "AlbumController.h"
#import <Three20/Three20.h>
#implementation Three20PhotoDemoAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch
TTNavigator* navigator = [TTNavigator navigator];
TTURLMap* map = navigator.URLMap;
[map from:#"demo://album" toViewController: [AlbumController class]];
[navigator openURLAction:[TTURLAction actionWithURLPath:#"demo://album"]];
return YES;
}
- (BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)URL {
[[TTNavigator navigator] openURLAction:[TTURLAction actionWithURLPath:URL.absoluteString]];
return YES;
}
- (void)dealloc {
[super dealloc];
}
#end
PhotoSource.h
#import <Three20/Three20.h>
#import <Three20/Three20+Additions.h>
typedef enum {
PhotoSourceNormal = 0,
PhotoSourceDelayed = 1,
PhotoSourceVariableCount = 2,
PhotoSourceLoadError = 4,
} PhotoSourceType;
#interface PhotoSource : TTURLRequestModel <TTPhotoSource> {
PhotoSourceType _type;
NSString* _title;
NSMutableArray* _photos;
NSArray* _tempPhotos;
NSTimer* _fakeLoadTimer;
}
- (id)initWithType:(PhotoSourceType)type title:(NSString*)title
photos:(NSArray*)photos photos2:(NSArray*)photos2;
#end
PhotoSource.m
import "PhotoSource.h"
#implementation PhotoSource
#synthesize title = _title;
- (void)fakeLoadReady {
_fakeLoadTimer = nil;
if (_type & PhotoSourceLoadError) {
[_delegates makeObjectsPerformSelector: #selector(model:didFailLoadWithError:)
withObject: self
withObject: nil];
} else {
NSMutableArray* newPhotos = [NSMutableArray array];
for (int i = 0; i < _photos.count; ++i) {
id<TTPhoto> photo = [_photos objectAtIndex:i];
if ((NSNull*)photo != [NSNull null]) {
[newPhotos addObject:photo];
}
}
[newPhotos addObjectsFromArray:_tempPhotos];
TT_RELEASE_SAFELY(_tempPhotos);
[_photos release];
_photos = [newPhotos retain];
for (int i = 0; i < _photos.count; ++i) {
id<TTPhoto> photo = [_photos objectAtIndex:i];
if ((NSNull*)photo != [NSNull null]) {
photo.photoSource = self;
photo.index = i;
}
}
[_delegates makeObjectsPerformSelector:#selector(modelDidFinishLoad:) withObject:self];
}
}
- (id)initWithType:(PhotoSourceType)type title:(NSString*)title photos:(NSArray*)photos
photos2:(NSArray*)photos2 {
if (self = [super init]) {
_type = type;
_title = [title copy];
_photos = photos2 ? [photos mutableCopy] : [[NSMutableArray alloc] init];
_tempPhotos = photos2 ? [photos2 retain] : [photos retain];
_fakeLoadTimer = nil;
for (int i = 0; i < _photos.count; ++i) {
id<TTPhoto> photo = [_photos objectAtIndex:i];
if ((NSNull*)photo != [NSNull null]) {
photo.photoSource = self;
photo.index = i;
}
}
if (!(_type & PhotoSourceDelayed || photos2)) {
[self performSelector:#selector(fakeLoadReady)];
}
}
return self;
}
- (id)init {
return [self initWithType:PhotoSourceNormal title:nil photos:nil photos2:nil];
}
- (void)dealloc {
[_fakeLoadTimer invalidate];
TT_RELEASE_SAFELY(_photos);
TT_RELEASE_SAFELY(_tempPhotos);
TT_RELEASE_SAFELY(_title);
[super dealloc];
}
- (BOOL)isLoading {
return !!_fakeLoadTimer;
}
- (BOOL)isLoaded {
return !!_photos;
}
- (void)load:(TTURLRequestCachePolicy)cachePolicy more:(BOOL)more {
if (cachePolicy & TTURLRequestCachePolicyNetwork) {
[_delegates makeObjectsPerformSelector:#selector(modelDidStartLoad:) withObject:self];
TT_RELEASE_SAFELY(_photos);
_fakeLoadTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self
selector:#selector(fakeLoadReady) userInfo:nil repeats:NO];
}
}
- (void)cancel {
[_fakeLoadTimer invalidate];
_fakeLoadTimer = nil;
}
- (NSInteger)numberOfPhotos {
if (_tempPhotos) {
return _photos.count + (_type & PhotoSourceVariableCount ? 0 : _tempPhotos.count);
} else {
return _photos.count;
}
}
- (NSInteger)maxPhotoIndex {
return _photos.count-1;
}
- (id<TTPhoto>)photoAtIndex:(NSInteger)photoIndex {
if (photoIndex < _photos.count) {
id photo = [_photos objectAtIndex:photoIndex];
if (photo == [NSNull null]) {
return nil;
} else {
return photo;
}
} else {
return nil;
}
}
#end
Photo.h
#import <Three20/Three20.h>
#interface Photo : NSObject <TTPhoto> {
id<TTPhotoSource> _photoSource;
NSString* _thumbURL;
NSString* _smallURL;
NSString* _URL;
CGSize _size;
NSInteger _index;
NSString* _caption;
}
- (id)initWithURL:(NSString*)URL smallURL:(NSString*)smallURL size:(CGSize)size;
- (id)initWithURL:(NSString*)URL smallURL:(NSString*)smallURL size:(CGSize)size
caption:(NSString*)caption;
#end
Photo.m
#import "Photo.h"
#implementation Photo
#synthesize photoSource = _photoSource, size = _size, index = _index, caption = _caption;
- (id)initWithURL:(NSString*)URL smallURL:(NSString*)smallURL size:(CGSize)size {
return [self initWithURL:URL smallURL:smallURL size:size caption:nil];
}
- (id)initWithURL:(NSString*)URL smallURL:(NSString*)smallURL size:(CGSize)size
caption:(NSString*)caption {
if (self = [super init]) {
_photoSource = nil;
_URL = [URL copy];
_smallURL = [smallURL copy];
_thumbURL = [smallURL copy];
_size = size;
_caption;
_index = NSIntegerMax;
}
return self;
}
- (void)dealloc {
TT_RELEASE_SAFELY(_URL);
TT_RELEASE_SAFELY(_smallURL);
TT_RELEASE_SAFELY(_thumbURL);
TT_RELEASE_SAFELY(_caption);
[super dealloc];
}
- (void)viewDidLoad {
}
- (NSString*)URLForVersion:(TTPhotoVersion)version {
if (version == TTPhotoVersionLarge) {
return _URL;
} else if (version == TTPhotoVersionMedium) {
return _URL;
} else if (version == TTPhotoVersionSmall) {
return _smallURL;
} else if (version == TTPhotoVersionThumbnail) {
return _thumbURL;
} else {
return nil;
}
}
#end
AlbumController.h
#import <Three20/Three20.h>
#interface AlbumController : TTPhotoViewController <UIActionSheetDelegate>{
NSArray *images;
UIBarButtonItem *_clickActionItem;
UIToolbar *_toolbar;
}
#property (nonatomic, retain) NSArray *images;
#property (nonatomic, retain) UIBarButtonItem *_clickActionItem;
#property (nonatomic, retain) UIToolbar *_toolbar;
#end
AlbumController.m
#import "AlbumController.h"
#import "PhotoSource.h"
#import "Photo.h"
#implementation AlbumController
#synthesize images;
- (void)loadView {
CGRect screenFrame = [UIScreen mainScreen].bounds;
self.view = [[[UIView alloc] initWithFrame:screenFrame]
autorelease];
CGRect innerFrame = CGRectMake(0, 0,
screenFrame.size.width,
screenFrame.size.height);
_innerView = [[UIView alloc] initWithFrame:innerFrame];
_innerView.autoresizingMask = UIViewAutoresizingFlexibleWidth|
UIViewAutoresizingFlexibleHeight;
[self.view addSubview:_innerView];
_scrollView = [[TTScrollView alloc] initWithFrame:screenFrame];
_scrollView.delegate = self;
_scrollView.dataSource = self;
_scrollView.backgroundColor = [UIColor blackColor];
_scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth|
UIViewAutoresizingFlexibleHeight;
[_innerView addSubview:_scrollView];
UIBarButtonItem *_actionButton = [[UIBarButtonItem alloc] initWithImage:
TTIMAGE(#"bundle://Three20.bundle/images/imageAction.png")
style:UIBarButtonItemStylePlain target:self action:#selector
(popupActionSheet)];
_nextButton = [[UIBarButtonItem alloc] initWithImage:
TTIMAGE(#"bundle://Three20.bundle/images/nextIcon.png")
style:UIBarButtonItemStylePlain target:self action:#selector
(nextAction)];
_previousButton = [[UIBarButtonItem alloc] initWithImage:
TTIMAGE(#"bundle://Three20.bundle/images/previousIcon.png")
style:UIBarButtonItemStylePlain target:self action:#selector
(previousAction)];
UIBarButtonItem* playButton = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:
UIBarButtonSystemItemPlay target:self action:#selector
(playAction)] autorelease];
playButton.tag = 1;
UIBarItem* space = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:
UIBarButtonSystemItemFlexibleSpace target:nil action:nil]
autorelease];
_toolbar = [[UIToolbar alloc] initWithFrame:
CGRectMake(0, screenFrame.size.height - TT_ROW_HEIGHT,
screenFrame.size.width, TT_ROW_HEIGHT)];
_toolbar.barStyle = self.navigationBarStyle;
_toolbar.autoresizingMask = UIViewAutoresizingFlexibleWidth|
UIViewAutoresizingFlexibleTopMargin;
_toolbar.items = [NSArray arrayWithObjects:
_actionButton, space, _previousButton, space,
_nextButton, space, nil];
[_innerView addSubview:_toolbar];
}
//(Just to add an action sheet)
//At the bottom of that codefile -- I added:
-(void)popupActionSheet {
UIActionSheet *popupQuery = [[UIActionSheet alloc]
initWithTitle:nil
delegate:self
cancelButtonTitle:#"Cancel"
destructiveButtonTitle:nil
otherButtonTitles:#"Save Image",nil];
popupQuery.actionSheetStyle = UIActionSheetStyleBlackOpaque;
[popupQuery showInView:self.view];
[popupQuery release];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:
(int)buttonIndex {
//UIImage* image = [[TTURLCache sharedCache] imageForURL:imageURL];
if (buttonIndex==0){
UIImage* thisImage = [[TTURLCache sharedCache] imageForURL:
[_centerPhoto URLForVersion:TTPhotoVersionLarge]];
UIImageWriteToSavedPhotosAlbum(thisImage, nil, nil, nil);
//{UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"URL"
//message:[_centerPhoto URLForVersion:TTPhotoVersionLarge] delegate:self cancelButtonTitle:#"No" ,otherButtonTitles:#"Yes", nil];
//[alert show];}
}
}
-(void)createPhotos {
images = [[NSArray alloc] initWithObjects:
[[[Photo alloc] initWithURL:#"bundle://14.png" smallURL:#"bundle://14.png"
size:CGSizeMake(320, 212)] autorelease],
[[[Photo alloc] initWithURL:#"bundle://30.png" smallURL:#"bundle://30.png"
size:CGSizeMake(320, 212)] autorelease],
[[[Photo alloc] initWithURL:#"bundle://back.jpeg" smallURL:#"bundle://back.jpeg"
size:CGSizeMake(319, 317)] autorelease],
nil];
}
- (void)viewDidLoad {
//[self loadView];
[self createPhotos]; // method to set up the photos array
self.photoSource = [[PhotoSource alloc]
initWithType:PhotoSourceNormal
title:#"SexyGirl"
photos:images
photos2:nil
];
}
#end
If all you need is to save an image to the Photos album, you can use:
UIImage *myImage;
UIImageWriteToSavedPhotosAlbum(myImage,nil,nil,nil);
If this is not your problem, then I don't get it. If you don't tell us where the problem is, posting three pages worth of code is pretty useless.

Issue adding a "$" to a tip calculator

I'm trying to add a "$" to a tip result in my app, but I'm having some difficulties. I'm next to Xcode and Objective-C, I am not exactly sure where I need to place the symbol with causing an error. Below is a copy of my .m code.
Any help is much appreciated
#import "tipcalcViewController.h"
#implementation tipcalcViewController
- (void)dealloc
{
[super dealloc];
}
- (IBAction)aSliderChanged:(id)sender {
UISlider *slider = (UISlider *)sender;
if (slider == tipslide) {
NSString *tip = [NSString stringWithFormat:#"%.2f", slider.value * 100];
int tipPercentage = [tip intValue];
NSString *multiplier;
if (tipPercentage < 10) {
multiplier = [NSString stringWithFormat:#"1.0%i", tipPercentage];
}
else if (tipPercentage >= 10) {
multiplier = [NSString stringWithFormat:#"1.%i", tipPercentage];
}
[costWithTipLabel setText:[NSString stringWithFormat:#"%.2f", ([[costWithoutTip text] intValue] * [multiplier floatValue])]];
[tipTextLabel setText:[[NSString stringWithFormat:#"Tip(%i", tipPercentage] stringByAppendingString:#"%):"]];
[self performSelector:#selector(updateNumOfPeop)];
}
else if (slider == peopleslide) {
NSString *p = [NSString stringWithFormat:#"%.f", slider.value*10];
int numberOfPeople = [p intValue];
[numberOfPeopleTextLabel setText:[NSString stringWithFormat:#"Each(%i):", numberOfPeople]];
[numberOfPeopleLabel setText:[NSString stringWithFormat:#"%.2f", [[costWithTipLabel text] floatValue]/numberOfPeople]];
}
[totalBillCost setText:[costWithTipLabel text]];
}
- (void)updateNumOfPeop {
NSString *p = [NSString stringWithFormat:#"%.f", peopleslide.value*10];
int numberOfPeople = [p intValue];
[numberOfPeopleTextLabel setText:[NSString stringWithFormat:#"Each(%i):", numberOfPeople]];
[numberOfPeopleLabel setText:[NSString stringWithFormat:#"%.2f", [[costWithTipLabel text] floatValue]/numberOfPeople]];
}
/*
- (IBAction)aSliderChanged:(id)sender {
UISlider *slider = (UISlider *)sender;
if (slider == tipslide) {
NSString *tip = [NSString stringWithFormat:#"%.f", slider.value * 100];
float tipPercentage = [tip floatValue];
NSString *multiplier = [NSString stringWithFormat:#"1.%.f", tipPercentage];
[costWithTipLabel setText:[NSString stringWithFormat:#"%.2f", [[costWithoutTip text] floatValue] * [multiplier floatValue]]];
[tipTextLabel setText:[[NSString stringWithFormat:#"Tip (%.f", slider.value *100]stringByAppendingString:#"%):"]];
}
else if (slider == peopleslide) {
NSString *p = [NSString stringWithFormat:#"%.f", slider.value*10];
float numOfPeople = [p floatValue];
[numberOfPeopleTextLabel setText:[NSString stringWithFormat:#"Each (%.f):", numOfPeople]];
[numberOfPeopleLabel setText:[NSString stringWithFormat:#"%.2f", [[costWithTipLabel text] floatValue]/numOfPeople]];
}
[totalBillCost setText:[NSString stringWithFormat:#"%.2f", [[costWithTipLabel text] floatValue]]];
}
*/
- (void)viewDidLoad {
[costWithoutTip becomeFirstResponder];
[costWithoutTip setDelegate:self];
[costWithoutTip setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];
[tipslide setValue:0.01];
[peopleslide setValue:0.1];
[super viewDidLoad];
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
[costWithoutTip setText:[NSString stringWithFormat:#"%.2f", [costWithoutTip text].floatValue]];
[costWithoutTip resignFirstResponder];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[costWithoutTip resignFirstResponder];
return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
[costWithoutTip resignFirstResponder];
return 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.
}
#pragma mark - View lifecycle
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
}
*/
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
If you're trying to format currency, use NSNumberFormatter.
NSNumber *someMoney = [NSNumber numberWithFloat:5.95];
NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSString *formattedAsDollars = [currencyFormatter stringFromNumber:someMoney];
[currencyFormatter release];
You can even venture into the world of NSDecimalNumber if you're feeling brave.