Set Background using camera roll images - objective-c

I want to know, how can I change my image app background using camera roll images. Any ideas??? How to get the camera roll paths or something like that!!!
Thanks!!!!

the following code uses a button on a toolbar, when pressed it will bring up the camera roll and then u will be able to pick the image to set
Start by adding the MobileCoreServices framework
add the following code in the .h file
#import <UIKit/UIKit.h>
#import <MobileCoreServices/MobileCoreServices.h>
#interface cameraViewController : UIViewController
<UIImagePickerControllerDelegate,
UINavigationControllerDelegate, UIPopoverControllerDelegate>
#property (nonatomic) BOOL newMedia;
#property (nonatomic, strong) IBOutlet UIImageView *imageView;
#property (nonatomic, strong) UIPopoverController *popoverController;
#property (nonatomic, strong) IBOutlet UIToolbar *toolbar;
- (IBAction)useCameraRoll: (id)sender;
#end
Add the following code in the .m file:
#synthesize imageView, popoverController, toolbar, newMedia;
- (IBAction) useCameraRoll: (id)sender
{
if ([self.popoverController isPopoverVisible]) {
[self.popoverController dismissPopoverAnimated:YES];
} else {
if ([UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypeSavedPhotosAlbum])
{
UIImagePickerController *imagePicker =
[[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType =
UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.mediaTypes = [NSArray arrayWithObjects:
(NSString *) kUTTypeImage,
nil];
imagePicker.allowsEditing = NO;
self.popoverController = [[UIPopoverController alloc]
initWithContentViewController:imagePicker];
self.popoverController.delegate = self;
[self.popoverController
presentPopoverFromBarButtonItem:sender
permittedArrowDirections:UIPopoverArrowDirectionUp
animated:YES];
newMedia = NO;
}
}
}
#pragma mark -
#pragma mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[self.popoverController dismissPopoverAnimated:true];
NSString *mediaType = [info
objectForKey:UIImagePickerControllerMediaType];
[self dismissModalViewControllerAnimated:YES];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
UIImage *image = [info
objectForKey:UIImagePickerControllerOriginalImage];
self.imageView.image = image;
if (newMedia)
UIImageWriteToSavedPhotosAlbum(image,
self,
#selector(image:finishedSavingWithError:contextInfo:),
nil);
}
else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
{
// Code here to support video if enabled
}
}
-(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];
}
Add the following in viewDidUnload:
- (void)viewDidUnload {
self.imageView = nil;
self.popoverController = nil;
self.toolbar = nil;
}
Dont forget to connect the imageview to your image and the cameraroll button to your button.

Check the docs for Assets Library.

-(void) uourCallingMethod{
UIImage *img = [UIImage imageNamed: [NSString stringWithFormat:#"image.jpg", i]];
UIImageWriteToSavedPhotosAlbum(img, nil, nil, nil);
}
(void) image:(UIImage *)image didFinishSavingWithError:(NSError *) error contextInfo:(void *) contextInfo{
}

Related

AVAssetWriter is always on AVAssetWriterStatusFailed status

my goal is to apply some filters on the camera input in real time. To do that step by step, I'm trying to get the input form the camera with AVFoundation record a video and save it in the camera roll. I tried, but for some reason the AVAssetWriter is always in AVAssetWriterStatusFailed and so the appendSampleBuffer: method always failed. Where is my error? Someone can help me?
Thanks!
ViewController.h
#import <UIKit/UIKit.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <AVFoundation/AVFoundation.h>
#interface ViewController : UIViewController <AVCaptureVideoDataOutputSampleBufferDelegate>
#property (weak, nonatomic) IBOutlet UIImageView *imageView;
#property (weak, nonatomic) IBOutlet UIButton *startRecButton;
#property (weak, nonatomic) IBOutlet UIButton *stopRecButton;
#property (weak, nonatomic) IBOutlet UIButton *startVideocamera;
- (IBAction)startRecordingButtonPressed:(UIButton *)sender;
- (IBAction)stopRecordingButtonPressed:(UIButton *)sender;
- (IBAction)startVideocameraButtonPressed:(UIButton *)sender;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#property (strong, nonatomic) AVAssetWriter* videoAssetWriter;
#property (strong, nonatomic) AVAssetWriterInput* videoAssetWriterInput;
#property (strong, nonatomic) NSURL* temporaryVideoURL;
#end
#implementation ViewController
#pragma mark - Variables
#synthesize imageView;
#synthesize videoAssetWriter;
#synthesize videoAssetWriterInput;
#synthesize temporaryVideoURL;
//initCaptureSession Method
AVCaptureSession* captureSession;
AVCaptureDevice* videoCaptureDevice;
AVCaptureDeviceInput* videoCaptureDeviceInput;
AVCaptureVideoDataOutput* videoDataOutput;
dispatch_queue_t videoQueue;
//captureOutput:didOutputSampleBuffer Method
CMSampleBufferRef currentSampleBuffer;
BOOL isRecording;
//newPixelBufferFromCGImage Method
CGAffineTransform frameTransform;
CGSize frameSize;
#pragma mark - User Interface
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)startRecordingButtonPressed:(UIButton *)sender {
[self initWriter];
}
- (IBAction)stopRecordingButtonPressed:(UIButton *)sender {
[self stopWriter];
}
- (IBAction)startVideocameraButtonPressed:(UIButton *)sender {
[self initCaptureSession];
}
#pragma mark - Capture Utils
-(void) initCaptureSession{
captureSession = [[AVCaptureSession alloc] init];
[captureSession setSessionPreset:AVCaptureSessionPreset1280x720];
videoCaptureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError* error;
videoCaptureDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:videoCaptureDevice error:&error];
if([captureSession canAddInput:videoCaptureDeviceInput]){
[captureSession addInput:videoCaptureDeviceInput];
}
videoDataOutput = [[AVCaptureVideoDataOutput alloc]init];
[captureSession addOutput:videoDataOutput];
videoQueue = dispatch_queue_create("videoQueue", NULL);
[videoDataOutput setAlwaysDiscardsLateVideoFrames:NO];
[videoDataOutput setSampleBufferDelegate:self queue:videoQueue];
NSString* key = (NSString*)kCVPixelBufferPixelFormatTypeKey;
NSNumber* value = [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA];
NSDictionary* videoSettings = [NSDictionary dictionaryWithObject:value forKey:key];
[videoDataOutput setVideoSettings:videoSettings];
[captureSession startRunning];
}
-(void) captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer: (CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection{
currentSampleBuffer = sampleBuffer;
CGImageRef image = [self imageFromSampleBuffer:currentSampleBuffer];
dispatch_sync(dispatch_get_main_queue(),
^{
if(!isRecording){
imageView.image = [UIImage imageWithCGImage: image scale:1.0 orientation:UIImageOrientationRight];
}
else{
imageView.image = [UIImage imageWithCGImage: image scale:1.0 orientation:UIImageOrientationRight];
// [videoAssetWriterInput appendSampleBuffer:currentSampleBuffer];
if (![videoAssetWriterInput appendSampleBuffer:sampleBuffer]) {
[self showError:[videoAssetWriter error]];
}
NSLog(#"%ld", (long)[videoAssetWriter status]);
}
});
CGImageRelease(image);
}
-(void)captureOutput:(AVCaptureOutput *)captureOutput didDropSampleBuffer: (CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection{
NSLog(#"didDropSampleBuffer CALLED");
}
#pragma mark - Writer Utils
-(void) initWriter{
temporaryVideoURL = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#%#", NSTemporaryDirectory(), #"Movie.MOV"]];
NSLog(#"%#", temporaryVideoURL);
NSError* error;
videoAssetWriter = [[AVAssetWriter alloc] initWithURL:temporaryVideoURL fileType:AVFileTypeQuickTimeMovie error:&error];
NSParameterAssert(videoAssetWriter);
NSLog(#"%ld", (long)[videoAssetWriter status]);
NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
AVVideoCodecH264, AVVideoCodecKey,
[NSNumber numberWithInt:1280], AVVideoWidthKey,
[NSNumber numberWithInt:720], AVVideoHeightKey,
nil];
videoAssetWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings];
NSParameterAssert(videoAssetWriterInput);
NSLog(#"%ld", (long)[videoAssetWriter status]);
if([videoAssetWriter canAddInput:videoAssetWriterInput]){
[videoAssetWriter addInput:videoAssetWriterInput];
}
isRecording = YES;
[videoAssetWriter startWriting];
NSLog(#"%ld", (long)[videoAssetWriter status]);
}
-(void) stopWriter{
[videoAssetWriterInput markAsFinished];
[videoAssetWriter finishWritingWithCompletionHandler:^{
NSLog(#"finishWritingWithCompletionHandler CALLED");
isRecording = NO;
[self saveVideoToCameraRoll];
videoAssetWriter =nil;
videoAssetWriterInput= nil;
}];
// [videoAssetWriter finishWriting];
// isRecording = NO;
// [self saveVideoToCameraRoll];
}
-(void) saveVideoToCameraRoll{
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeVideoAtPathToSavedPhotosAlbum:temporaryVideoURL completionBlock:^(NSURL *assetURL, NSError *error){
NSLog(#"ASSET URL: %#", [assetURL path]);
if(error) {
NSLog(#"CameraViewController: Error on saving movie : %# {imagePickerController}", error);
}
else {
NSLog(#"Video salvato correttamente in URL: %#", assetURL);
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:[temporaryVideoURL path]];
NSLog(#"IL FILE ESISTE: %hhd", fileExists);
NSLog(#"E PESA: %#", [[[NSFileManager defaultManager] attributesOfItemAtPath: [temporaryVideoURL path] error:&error] objectForKey:NSFileSize]);
}
}];
}
This error is because of a reason that a file with similar filename already exist.
In my case, I was using a static file name for testing purpose, which caused the error. Making it something unique something like:
"\(Date().timeIntervalSince1970).mp4" fixed it.

No known class method for selector 'sharedStore'

Have a singleton class for BNRItemStore, but when I tried to call it, I get the above error which causes an ARC issue. Have commented out the error.
DetailViewController.m
#import "DetailViewController.h"
#import "BNRItem.h"
#import "BNRImageStore.h"
#import "BNRItemStore.h"
#implementation DetailViewController
#synthesize item;
-(id)initForNewItem:(BOOL)isNew
{
self = [super initWithNibName:#"DetailViewController" bundle:nil];
if(self){
if (isNew) {
UIBarButtonItem *doneItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self
action:#selector(save:)];
[[self navigationItem] setRightBarButtonItem:doneItem];
UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
target:self
action:#selector(cancel:)];
[[self navigationItem] setLeftBarButtonItem:cancelItem];
}
}
return self;
}
-(id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)bundle
{
#throw [NSException exceptionWithName:#"Wrong initializer"
reason:#"Use initForNewItem:"
userInfo:nil];
return nil;
}
-(void)viewDidLoad
{
[super viewDidLoad];
UIColor *clr = nil;
if ([[UIDevice currentDevice]userInterfaceIdiom]== UIUserInterfaceIdiomPad) {
clr = [UIColor colorWithRed:0.875 green:0.88 blue:0.91 alpha:1];
} else {
clr = [UIColor groupTableViewBackgroundColor];
}
[[self view]setBackgroundColor:clr];
}
- (void)viewDidUnload {
nameField = nil;
serialNumberField = nil;
valueField = nil;
dateLabel = nil;
imageView = nil;
[super viewDidUnload];
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[nameField setText:[item itemName]];
[serialNumberField setText:[item serialNumber]];
[valueField setText:[NSString stringWithFormat:#"%d", [item valueInDollars]]];
// Create a NSDateFormatter that will turn a date into a simple date string
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
// Use filtered NSDate object to set dateLabel contents
[dateLabel setText:[dateFormatter stringFromDate:[item dateCreated]]];
NSString *imageKey = [item imageKey];
if (imageKey) {
// Get image for image key from image store
UIImage *imageToDisplay = [[BNRImageStore sharedStore]imageForKey:imageKey];
// Use that image to put on the screen in imageview
[imageView setImage:imageToDisplay];
} else {
// Clear the imageview
[imageView setImage:nil];
}
}
-(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
// Clear first responder
[[self view]endEditing:YES];
// "Save" changes to item
[item setItemName:[nameField text]];
[item setSerialNumber:[serialNumberField text]];
[item setValueInDollars:[[valueField text] intValue]];
}
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)io
{
if ([[UIDevice currentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPad) {
return YES;
} else {
return (io==UIInterfaceOrientationPortrait);
}
}
-(void)setItem:(BNRItem *)i
{
item = i;
[[self navigationItem] setTitle:[item itemName]];
}
- (IBAction)takePicture:(id)sender {
if ([imagePickerPopover isPopoverVisible]) {
// If the popover is already up, get rid of it
[imagePickerPopover dismissPopoverAnimated:YES];
imagePickerPopover = nil;
return;
}
UIImagePickerController *imagePicker =
[[UIImagePickerController alloc]init];
// If our device has a camera, we want to take a picture, otherwise, we
// just pick from the photo library
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
[imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
} else {
[imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
// This line of code will generate a warning right now, ignore it
[imagePicker setDelegate:self];
//Place image picker on the screen
// Check for iPad device before instantiating the popover controller
if ([[UIDevice currentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPad) {
// Create a new popover controller that will display the imagepicker
imagePickerPopover = [[UIPopoverController alloc]initWithContentViewController:imagePicker];
[imagePickerPopover setDelegate:self];
// Display the popover controller; sender
// is the camera bar button item
[imagePickerPopover presentPopoverFromBarButtonItem:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
} else {
[self presentViewController:imagePicker animated:YES completion:nil];
}
}
}
-(void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController
{
NSLog(#"User dismissed popover");
imagePickerPopover = nil;
}
- (IBAction)backgroundTapped:(id)sender {
[[self view]endEditing:YES];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *oldKey = [item imageKey];
// Did the item already have an image?
if (oldKey) {
// Delete the old image
[[BNRImageStore sharedStore]deleteImageForKey:oldKey];
}
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
// Create a CFUUID object - it knows how to create unique identifier strings
CFUUIDRef newUniqueID = CFUUIDCreate(kCFAllocatorDefault);
// Create a string from unique identifier
CFStringRef newUniqueIDString = CFUUIDCreateString(kCFAllocatorDefault, newUniqueID); // Incompatible integer to pointer conversion initializing
// Use that unique ID to set our item's imageKey
NSString *key = (__bridge NSString *)newUniqueIDString;
[item setImageKey:key];
// Store image in the BNRImageStore with this key
[[BNRImageStore sharedStore] setImage:image forKey:[item imageKey]];
CFRelease(newUniqueIDString);
CFRelease(newUniqueID);
[imageView setImage:image];
if ([[UIDevice currentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPad) {
// If on the phone, the image picker is presented modally. Dismiss it.
[self dismissViewControllerAnimated:YES completion:nil];
} else {
// If on the pad, the image picker is in the popover. Dismiss the popover.
[imagePickerPopover dismissPopoverAnimated:YES];
imagePickerPopover = nil;
}
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
-(void)save:(id)sender
{
[[self presentingViewController]dismissViewControllerAnimated:YES
completion:nil];
}
-(void)cancel:(id)sender
{
// If the user cancelled, then remove the BNRItem from the store
[[BNRItemStore sharedStore]removeItem:item]; // No known class method for selector 'sharedStore'
[[self presentingViewController]dismissViewControllerAnimated:YES completion:nil];
}
DetailViewController.h
#import <UIKit/UIKit.h>
#class BNRItem;
#interface DetailViewController : UIViewController <UINavigationControllerDelegate, UIImagePickerControllerDelegate,UITextFieldDelegate, UIPopoverControllerDelegate>
{
__weak IBOutlet UITextField *nameField;
__weak IBOutlet UITextField *serialNumberField;
__weak IBOutlet UITextField *valueField;
__weak IBOutlet UILabel *dateLabel;
__weak IBOutlet UIImageView *imageView;
UIPopoverController *imagePickerPopover;
}
#property(nonatomic,strong)BNRItem *item;
-(id)initForNewItem:(BOOL)isNew;
- (IBAction)takePicture:(id)sender;
- (IBAction)backgroundTapped:(id)sender;
#end
BNRItemStore.m
#import "BNRItemStore.h"
#import "BNRItem.h"
#implementation BNRItemStore
+ (BNRItemStore *)defaultStore
{
static BNRItemStore *defaultStore = nil;
if(!defaultStore)
defaultStore = [[super allocWithZone:nil] init];
return defaultStore;
}
+ (id)allocWithZone:(NSZone *)zone
{
return [self defaultStore];
}
- (id)init
{
self = [super init];
if(self) {
allItems = [[NSMutableArray alloc] init];
}
return self;
}
- (void)removeItem:(BNRItem *)p
{
[allItems removeObjectIdenticalTo:p];
}
- (NSArray *)allItems
{
return allItems;
}
- (void)moveItemAtIndex:(int)from
toIndex:(int)to
{
if (from == to) {
return;
}
// Get pointer to object being moved so we can re-insert it
BNRItem *p = [allItems objectAtIndex:from];
// Remove p from array
[allItems removeObjectAtIndex:from];
// Insert p in array at new location
[allItems insertObject:p atIndex:to];
}
- (BNRItem *)createItem
{
BNRItem *p = [BNRItem randomItem];
[allItems addObject:p];
return p;
}
#end
BNRItemStore.h
#import <Foundation/Foundation.h>
#class BNRItem;
#interface BNRItemStore : NSObject
{
NSMutableArray *allItems;
}
+ (BNRItemStore *)defaultStore;
- (void)removeItem:(BNRItem *)p;
- (NSArray *)allItems;
- (BNRItem *)createItem;
- (void)moveItemAtIndex:(int)from
toIndex:(int)to;
#end
You are calling +sharedStore on BNRItemStore where your error occurs. This is because it really does not exist according to the code you posted.
All of the others calling +sharedStore are using the one presumably made available by BNRImageStore which you didn't provide. I assume it exists in that class? :)
In short, change:
[[BNRItemStore sharedStore]removeItem:item];
to
[[BNRImageStore sharedStore]removeItem:item];

Alert View button actions not working

I am using an Alert view to bring up a popup where the user will choose to either select a photo from the library or take a photo to use. The alert view comes up fine, but when I select a button the code I have implemented is not run?!?
for some reason the - (void)picturePopup:(UIAlertView *)picturePopup clickedButtonAtIndex:(NSInteger)buttonIndex does not seem to even get run!? I'm lost run over lots of tutorials and websites but can't see why?! please help!
code:
.m
#import "LoadViewController.h"
#implementation LoadViewController
int imageCase;
- (IBAction)pick:(id) sender {
imageCase = [sender tag];
UIAlertView *picturePopup = [[UIAlertView alloc]
initWithTitle:#"Select Photo" message:nil delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Choose From Library", #"Take Photo", nil];
[picturePopup show];
}
- (void)picturePopup:(UIAlertView *)picturePopup clickedButtonAtIndex:(NSInteger)buttonIndex {
NSLog(#"***************getting here****************");
if (buttonIndex == 1) {
NSLog(#"***************library****************");
//Library Picker
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentModalViewController:picker animated:YES];
}
if (buttonIndex == 2) {
NSLog(#"***************camera****************");
//Camera
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentModalViewController:picker animated:YES];
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
switch (imageCase) {
case 1:
imageView1.image = image;
break;
case 2:
imageView2.image = image;
break;
}
[picker.parentViewController dismissModalViewControllerAnimated:YES];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker.parentViewController dismissModalViewControllerAnimated:YES];
}
#end
.h
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#interface LoadViewController : UIViewController <UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIAlertViewDelegate> {
IBOutlet UIImageView *imageView1;
IBOutlet UIImageView *imageView2;
}
- (IBAction)pick:(id) sender;
#end
You need to use the actual delegate method:
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
This is not the same as:
- (void)picturePopup:(UIAlertView *)picturePopup clickedButtonAtIndex:(NSInteger)buttonIndex
The method signatures are different. alertView:clickedButtonAtIndex: vs. picturePopup:clickedButtonAtIndex:
You can rename the variable you just can not change the method signature.
This is sort of off topic, but I notice you didn't synthesize *imageView1 and *imageView2. lol

After setting UITextView's text property, screen does not update accordingly

I have view controllers A(FileListViewController) and B(TextFileViewController). A is a UITableViewController. What I am doing now is that after selecting a row in controller A, I load a text file and display that text in a UITextView in controller B.
The following is the header and implementation part(some code is abridged) of my the two controllers.
FileListViewcontroller Interface:
#interface FileListViewController : UITableViewController {
NSMutableArray * fileList;
DBRestClient* restClient;
TextFileViewController *tfvc;
}
#property (nonatomic, retain) NSMutableArray * fileList;
#property (nonatomic, retain) TextFileViewController *tfvc;
#end
FileListViewController Implementation:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
DBMetadata *metaData = [fileList objectAtIndex:indexPath.row];
if(!metaData.isDirectory){
if([Utils isTextFile:metaData.path]){
if(!tfvc){
tfvc = [[TextFileViewController alloc] init];
}
[self restClient].delegate = self;
[[self restClient] loadFile:metaData.path intoPath:filePath];
[self.navigationController pushViewController:tfvc animated:YES];
}
}
- (void)restClient:(DBRestClient*)client loadedFile:(NSString*)destPath {
NSError *err = nil;
NSString *fileContent = [NSString stringWithContentsOfFile:destPath encoding:NSUTF8StringEncoding error:&err];
if(fileContent) {
[tfvc updateText:fileContent];
} else {
NSLog(#"Error reading %#: %#", destPath, err);
}
}
And here is the interface for TextFileViewController:
#interface TextFileViewController : UIViewController {
UITextView * textFileView;
}
#property (nonatomic, retain) IBOutlet UITextView * textFileView;
-(void) updateText:(NSString *) newString;
#end
TextFileViewController implementation:
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(done)] autorelease];
textFileView = [[UITextView alloc] init];
}
- (void) updateText:(NSString *)newString {
NSLog(#"new string has value? %#", newString);
[textFileView setText:[NSString stringWithString:newString]];
NSLog(#"print upddated text of textview: %#", textFileView.text);
[[self textFileView] setNeedsDisplay];
}
(void)restClient: loadedFile: will be call after the loadFile:intoPath: is completed in the disSelectRowAtIndexPath method.
In TextFileViewController's updateText method, from NSLog I see that the text property is updated correctly. But the screen does not update accordingly. I've tried setNeedsDisplay but in vain. Did I miss something?
Thanks in advance.
In -[TextFileViewController viewDidLoad] you're creating a UITextView, but its frame is never set, and it's not added to the view hierarchy.
Try changing this:
textFileView = [[UITextView alloc] init];
to this:
textFileView = [[UITextView alloc] initWithFrame:[[self view] bounds]];
[[self view] addSubview:textFileView];
The problem is that textFileView is created in the viewDidLoad method of TextFileViewController. This method has not yet been called by the time you call updateText (this happens before the TextFileViewController is pushed).
You can fix this by forcing the view to load before you call [[self restClient] loadFile:metaData.path intoPath:filePath];.

UIView Shows perfect on the Simulator, but not iPhone?

Okay,
I have a really weird problem. When switching over to a different XIB, it shows on simulator but not on my test device. I will provide some code and screenshots of my layout in interface builder! Thanks in advance.
SettingViewController (what get's called to be displayed)
DetailViewController (what calls SettingsViewController to be displayed)
SettingsViewController.h
//
// SettingsViewController.h
//
// Created by Coulton Vento on 2/26/11.
// Copyright 2011 Your Way Websites. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "TableViewAppDelegate.h"
#import "Sqlite.h"
#class SettingsStoreViewController;
#interface SettingsViewController : UIViewController {
}
#end
SettingsViewController.m
#import "SettingsViewController.h"
#import "TableViewAppDelegate.h"
#implementation SettingsViewController
- (void)viewDidLoad {
NSString *myDB = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"flashpics.db"];
database = [[Sqlite alloc] init];
[database open:myDB];
TableViewAppDelegate *dataCeter = (TableViewAppDelegate *)[[UIApplication sharedApplication] delegate];
myTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector: #selector(updateNumber) userInfo: nil repeats: YES];
self.navigationItem.title = #"Album Settings";
NSString *post =[NSString stringWithFormat:#"id=%#", dataCeter.dataTwo];
NSString *hostStr = #"http://myflashpics.com/iphone_processes/get_album.php?";
hostStr = [hostStr stringByAppendingString:post];
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
if ([serverOutput rangeOfString:#"yes"].location == NSNotFound) {
//NSLog(#"Fail - %# / %#", usernameField.text, passwordField.text);
UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Please check your internet connection" delegate:self cancelButtonTitle:#"Try Again" otherButtonTitles:nil, nil];
[alertsuccess show];
[alertsuccess release];
[alertsuccess setTag:6];
} else {
NSArray *myWords = [serverOutput componentsSeparatedByString:#"?!?divide?!?"];
NSString *albumNameResults = [myWords objectAtIndex:1];
NSString *albumCommentsResults = [myWords objectAtIndex:2];
NSString *albumPrivateResults = [myWords objectAtIndex:3];
NSString *numberOfConnections = [myWords objectAtIndex:4];
albumName.text = albumNameResults;
numberButton.text = numberOfConnections;
if ([numberOfConnections isEqualToString:#"1"]) {
connectionsButton.text = #"Connection";
} else {
connectionsButton.text = #"Connections";
}
if ([albumCommentsResults isEqualToString:#"yes"]) {
[albumComments setOn:YES animated:YES];
} else {
[albumComments setOn:NO animated:YES];
}
if ([albumPrivateResults isEqualToString:#"yes"]) {
[albumPrivate setOn:YES animated:YES];
} else {
[albumPrivate setOn:NO animated:YES];
}
}
}
DetailViewController.h
#import <UIKit/UIKit.h>
#import "Sqlite.h"
#import "OHGridView.h"
#import "BigView.h"
#import "SettingsViewController.h"
#import "processViewController.h"
#class SecondView;
#class BigView;
#class CaptionView;
#interface DetailViewController : UIViewController <OHGridViewDelegate, OHGridViewDataSource> {
}
#end
DetailViewController.m
//
// DetailViewController.m
// TableView
//
// Created by iPhone SDK Articles on 1/17/09.
// Copyright www.iPhoneSDKArticles.com 2009.
//
#import "DetailViewController.h"
#import "TableViewAppDelegate.h"
#import "processViewController.h"
#implementation DetailViewController
#synthesize selectedCountry;
#synthesize selectedID;
- (IBAction)switchViews {
[self presentModalViewController:bigView animated:YES];
}
- (void)viewWillAppear {
[(OHGridView *)self.view reloadData];
NSLog(#" --- %# --- ", items);
}
- (IBAction)showSettings {
TableViewAppDelegate *dataCeter = (TableViewAppDelegate *)[[UIApplication sharedApplication] delegate];
dataCeter.dataTwo = selectedID;
SettingsViewController *screentwothree = [[SettingsViewController alloc] initWithNibName:nil bundle:nil];
screentwothree.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:screentwothree animated:YES];
[screentwothree release];
//[self.navigationController pushViewController:screentwothree animated:YES];
//[screentwothree release];
//screentwothree = nil;
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
- (void)dealloc {
[selectedCountry release];
[lblText release];
[super dealloc];
}
#end
Sorry for all the code.
This sort of thing is often due to a difference in file systems: MacOS is typically case-insensitive, while iOS is always case-sensitive. So if you specify the .xib as "myview.xib" but it's actual name is "MyView.xib", that'll generally work on the simulator but not on the device. Same thing happens with images and other resources.