I can't wrap my head around the issue here: I save a PDF to disk - then load I try to load the PDF on a physical device and turn on airplane mode. File doesn't load. Can you help me ? It's clearly an issue of saving to and retrieving from the same directory.
SAVE LOCATION RETURNS:
Save location is : /var/mobile/Containers/Data/Application/A1F1B294-9282-483B-B2E1-76C586A9631E/Documents/fileurl.pdf
LOADING DIRECTORY RETURNS :
filePath is : /var/mobile/Containers/Data/Application/A1F1B294-9282-483B-B2E1-76C586A9631E/Documents/var/mobile/Containers/Data/Application/A1F1B294-9282-483B-B2E1-76C586A9631E/Documents/fileurl.pdf
SAVING THE PDF:
PDFViewController.m
- (IBAction)download:(id)sender {
NSManagedObjectContext *context = [self managedObjectContext];
NSError *error = nil;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"Downloads"];
[request setPredicate:[NSPredicate predicateWithFormat:#"pubnumber = %#", self.title]];
[request setFetchLimit:1];
NSUInteger count = [context countForFetchRequest:request error:&error];
if (count == NSNotFound) {
} else if (count == 0) {
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[
NSURL URLWithString:self.pdfURL]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* filePath = [documentsDirectory stringByAppendingPathComponent:self.pdfURL];
[pdfData writeToFile:filePath atomically:YES];
NSLog(#"Save location is : %#", filePath);
NSManagedObject *newDWNLD = [NSEntityDescription insertNewObjectForEntityForName:#"Downloads" inManagedObjectContext:context];
[newDWNLD setValue:self.title forKey:#"pubnumber"];
[newDWNLD setValue:titleString forKey:#"pubtitle"];
[newDWNLD setValue:filePath forKey:#"puburl"];
if (![context save:&error]) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Can't Save" message:#"Error handeling this request" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
alertView.tag = 2;
[alertView show];
}
} else {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Stand Fast!" message:#"This document is already in your Downloads library" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
alertView.tag = 2;
[alertView show];
}
}
LOADING THE PDF:
DownloadsTableViewController.m
#import "PDFViewController.h"
#interface DownloadsTableViewController ()
#property (strong) NSMutableArray *downloads;
#property (weak) NSString *filePath;
#end
-(void)viewDidAppear:(BOOL)animated {
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:#"DWNLDView"];
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Downloads"];
self.downloads = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
self.filePath = [self.downloads valueForKey:#"puburl"];
[self.tableView reloadData];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"DWNLDView"];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
PDFViewController *pdfVC = [storyboard instantiateViewControllerWithIdentifier:#"PDFViewController"];
pdfVC.title = cell.textLabel.text;
pdfVC.DWNLDSpassedURL = self.filePath;
pdfVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
pdfVC.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentViewController:pdfVC animated:YES completion:nil];
}
PDFViewController.h
#import "MBProgressHUD.h"
#import <CoreData/CoreData.h>
#import <Parse/Parse.h>
#import <MessageUI/MessageUI.h>
<UIWebViewDelegate, UIAlertViewDelegate, MFMailComposeViewControllerDelegate>
#property (weak, nonatomic) NSString *DWNLDSpassedURL;
PDFViewController.m
- (void)viewDidLoad {
if ([[DWNLDed objectForKey:#"DWNLDView"] isEqual:#YES]) {
[self LocalQuery];
}
}
- (void)LocalQuery {
NSLog(#"Local Query initiated");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* filePath = [documentsDirectory stringByAppendingPathComponent:DWNLDSpassedURL];
NSLog(#"filePath is : %#", filePath);
NSURL *loadURL = [NSURL fileURLWithPath:filePath];
NSURLRequest *localDOC = [NSURLRequest requestWithURL:loadURL];
[self.webView loadRequest:localDOC];
}
Check your filePath in (void)LocalQuery I think it's not true
DownloadsTableViewController.m
tableView:didSelectRowAtIndexPath: set DWNLDSpassedURL = self.filePath
PDFViewController.m
NSString* filePath = [documentsDirectory stringByAppendingPathComponent:DWNLDSpassedURL]; can't get true document filePath
//documentsDirectory : /var/mobile/Containers/Data/Application/A1F1B294-9282-483B-B2E1-76C586A9631E/Documents/
//DWNLDSpassedURL: /var/mobile/Containers/Data/Application/A1F1B294-9282-483B-B2E1-76C586A9631E/Documents/fileurl.pdf
try this link
EDIT:
Solution:
PDFViewController.m
use NSString* filePath = DWNLDSpassedURL; instead NSString* filePath = [documentsDirectory stringByAppendingPathComponent:DWNLDSpassedURL];
OR
DownloadsTableViewController.m tableView:(UITableView *)tableView didSelectRowAtIndexPath:
pdfVC.DWNLDSpassedURL = yourFileName;
Related
This is for my iOS app using Core Data.
I'm getting some extra information in my CSV export that I'd like to remove. Below is my code and an example of what I am seeing.
Code:
NSOutputStream *stream = [[NSOutputStream alloc] initToMemory];
CHCSVWriter *writer = [[CHCSVWriter alloc] initWithOutputStream:stream encoding:NSUTF8StringEncoding delimiter:','];
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Notes"];
self.fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:nil];
for (NSString *instance in self.fetchedObjects) {
[writer writeLineOfFields:#[instance.description]];
}
[writer closeStream];
NSData *buffer = [stream propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
NSString *output = [[NSString alloc] initWithData:buffer encoding:NSUTF8StringEncoding];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
NSString * csvPath = [documentsDirectory stringByAppendingPathComponent:#"mydata.csv"];
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController * mailView = [[MFMailComposeViewController alloc] init];
mailView.mailComposeDelegate = self;
[[mailView navigationBar] setTintColor:[UIColor whiteColor]];
[mailView setSubject:#"My Subject Line"];
if (![[NSFileManager defaultManager] fileExistsAtPath:csvPath]) {
[[NSFileManager defaultManager] createFileAtPath:csvPath contents:nil attributes:nil];
}
BOOL res = [[output dataUsingEncoding:NSUTF8StringEncoding] writeToFile:csvPath atomically:NO];
if (!res) {
[[[UIAlertView alloc] initWithTitle:#"Error Creating CSV" message:#"Check your permissions to make sure this app can create files so you may email the app data" delegate:nil cancelButtonTitle:#"Okay" otherButtonTitles: nil] show];
} else{
NSLog(#"Data saved! File path = %#", csvPath);
[mailView addAttachmentData:[NSData dataWithContentsOfFile:csvPath] mimeType:#"text/csv" fileName:#"mydata.csv"];
[self presentViewController:mailView animated:YES completion:nil];
}
} else {
UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:#"Mail Error" message:#"Your device is not configured to send mail." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
Output Example:
<Notes: 0x1c009fb30> (entity: Notes; id: 0xd000000000080000 <x-coredata://597EDC54-FFDE-43FA-8C61-DE67763C1D13/Notes/p2> ; data: {
// My data shows here.
})
What I want:
I just want the saved data from the user input. Not the extra data about the entity, id, etc.
Also:
My data does not load in the email initially. I have to go into my UIViewController and then when I go to my Settings page and send the email the data shows. What would cause this?
You're getting that result because you're relying the description method to get information about your objects. That method produces a string, and the string is what you're seeing-- something that's not CSV, or easy to convert to CSV.
I'm not familiar with CHCSVParser but it looks like you might want to override description in your Notes class to produce something that CHCSVParser can handle. The default implementation on NSManagedObject-- which is what you're using now-- is not a good choice for this situation.
In my app I am using sqlite database and core data for showing data in database and every thing ok.
I want user to be able to add photo in document directory of app, so I defined two model for app.
I used this link http://blog.atwam.com/blog/2012/05/11/multiple-persistent-stores-and-seed-data-with-core-data/
and also PhotoLocations from Apple sample code(https://developer.apple.com/library/ios/samplecode/PhotoLocations/Introduction/Intro.html) for add photo functionality.
Showing data from sql is fine but when I add another model to app and manipulate AppDelegate , app crashes.
I don't want to use MagicalRecord because I am more than half way with core data .
Here is my original AppDelegate:
// AppDelegate.m
// iranbirds
//
// Created by Mehdi on 7/31/16.
// Copyright © 2016 Mehdi. All rights reserved.
//
#import "AppDelegate.h"
#import "BirdsTableViewController.h"
#import "GeneralViewController.h"
#import "FavoriteTableViewController.h"
#import "MapViewController.h"
#import "MoreViewController.h"
//#import "Bird.h" //maybe delete
#import "BirdInfo.h"
#import "BirdImage.h"
#import "Favorite.h"
#import <CoreData/CoreData.h>
#interface AppDelegate () //class extension
#property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, strong) NSManagedObjectModel *managedObjectModel;
#property (nonatomic, strong) NSPersistentStoreCoordinator *persistentStoreCoordinator;
#property (nonatomic, strong) NSArray *fetchedObjects;
#end
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
UINavigationController *naviController = (UINavigationController *)tabBarController.viewControllers[0];
naviController = (UINavigationController *)tabBarController.viewControllers[0];
BirdsTableViewController *catalogViewController = (BirdsTableViewController *)[naviController topViewController];
// catalogViewController.managedojbectContext = self.managedObjectContext;
//pass managed context to species view controller
naviController = (UINavigationController *)tabBarController.viewControllers[0];
MapViewController *mapViewController = (MapViewController *)[naviController topViewController];
mapViewController.managedOjbectContext = self.managedObjectContext;
naviController = (UINavigationController *)tabBarController.viewControllers[0];
FavoriteTableViewController *favoriteViewcontroller = (FavoriteTableViewController *)[naviController topViewController];
favoriteViewcontroller.managedOjbectContext = self.managedObjectContext;
//pass managed context view controller
naviController = (UINavigationController *)tabBarController.viewControllers[0];
MoreViewController *moreViewController = (MoreViewController *)[naviController topViewController];
moreViewController.managedOjbectContext = self.managedObjectContext;
//pass managed context view controller
naviController = (UINavigationController *)tabBarController.viewControllers[0];
APLViewController *aplViewController = (APLViewController *)[naviController topViewController];
aplViewController.managedOjbectContext = self.managedObjectContext;
return YES;
}
- (void)applicationWillTerminate:(UIApplication *)application {
}
#pragma mark - Core Data stack
- (NSManagedObjectModel *)managedObjectModel {
if (_managedObjectModel == nil) {
NSString *modelPath = [[NSBundle mainBundle] pathForResource:#"TaxonModel" ofType:#"mom"];
NSURL *modelUrl = [NSURL fileURLWithPath:modelPath];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelUrl];
}
return _managedObjectModel;
}
- (NSString *)documentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths lastObject];
//NSLog(#"document directory: %#", documentsDirectory);
return documentsDirectory;
}
- (NSString *)dataStorePath
{
return [[self documentsDirectory] stringByAppendingPathComponent:#"DataStore.sqlite"];
}
/**
Returns the persistent store coordinator for the application.
If the coordinator doesn't already exist, it is created and the application's store added to it.
*/
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
if (_persistentStoreCoordinator == nil) {
//if the expected store doesn't exist, copy the default store from main bundle
if (![[NSFileManager defaultManager] fileExistsAtPath:[self dataStorePath]]) {
NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:#"DataStore" ofType:#"sqlite"]; // we construct a path to our database file We’re storing the database in our application’s bundle,o we use the pathForResource method to obtain the path.
if (defaultStorePath) {
[[NSFileManager defaultManager] copyItemAtPath:defaultStorePath toPath:[self dataStorePath] error:NULL];
}
}
NSURL *storeUrl = [NSURL fileURLWithPath:[self dataStorePath]];
// NSURL *storeUrl= [[self applicationDirectory] URLByAppendingPathComponent:#"Card.sqlite"];
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];
NSError *error;
//NSDictionary *options = #{NSSQLitePragmasOption:#{#"journal_mode":#"DELETE"}};
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeUrl
options:nil
error:&error]) {
//NSLog(#"Error adding persistent store %#, %#", error, [error userInfo]);
abort();
}
}
[self addSkipBackupAttributeToItemAtPath:[self dataStorePath]];
return _persistentStoreCoordinator;
}
- (BOOL)addSkipBackupAttributeToItemAtPath:(NSString *) filePathString
{
NSURL* URL= [NSURL fileURLWithPath:filePathString];
assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
NSError *error = nil;
BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
forKey: NSURLIsExcludedFromBackupKey error: &error];
if(!success){
NSLog(#"Error excluding %# from backup %#", [URL lastPathComponent], error);
}
//NSLog(#"Added %#",[NSNumber numberWithBool: success]);
return success;
}
- (NSManagedObjectContext *)managedObjectContext
{
if (_managedObjectContext == nil) {
NSPersistentStoreCoordinator *coordinator = self.persistentStoreCoordinator;
if (coordinator !=nil) {
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
}
return _managedObjectContext;
}
- (void)preloadData {
NSString *path = [[NSBundle mainBundle] pathForResource:#"acachecklist" ofType:#"txt"];
NSError *error;
NSString *allBirds = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
if (allBirds == nil) {
//NSLog(#"Error reading file: %#",[error localizedDescription]);
}
NSArray *lines=[allBirds componentsSeparatedByString:#"\n"];
unsigned long count = [lines count];
NSArray *bird;
for(int i=0;i<count;i++) {
bird=[[lines objectAtIndex:i] componentsSeparatedByString:#"\t"];
BirdInfo *info = [NSEntityDescription insertNewObjectForEntityForName:#"BirdInfo"
inManagedObjectContext:self.managedObjectContext];
BirdImage *imageObj = [NSEntityDescription insertNewObjectForEntityForName:#"BirdImage"
inManagedObjectContext:self.managedObjectContext];
UIImage *tempImage = [UIImage imageNamed:#"Placeholder"];
imageObj.image = UIImageJPEGRepresentation(tempImage,1);
info.category = [bird objectAtIndex:0];
info.com_name = [bird objectAtIndex:1];
info.sci_name = [bird objectAtIndex:2];
//info.taxon_id = [bird objectAtIndex:2];
info.thumbnailImage = imageObj;
NSError *error;
if (![self.managedObjectContext save:&error]) {
//NSLog(#"Error: %#", error);
abort();
}
}
}
- (void)preLoadSpecies
{
NSManagedObjectContext *privateContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
privateContext.persistentStoreCoordinator = self.managedObjectContext.persistentStoreCoordinator;
NSEntityDescription *entity = [NSEntityDescription insertNewObjectForEntityForName:#"BirdInfo"
inManagedObjectContext:self.managedObjectContext];
NSFetchRequest *allSpeciesRequest = [[NSFetchRequest alloc] init];
[allSpeciesRequest setEntity:entity];
[privateContext performBlock:^{
NSError *error;
self.fetchedObjects = [privateContext executeFetchRequest:allSpeciesRequest error:&error];
if (error) {
//NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}];
}
#end
AppDelegate after edit:
#import "AppDelegate.h"
#import "BirdsTableViewController.h"
#import "GeneralViewController.h"
#import "FavoriteTableViewController.h"
#import "MapViewController.h"
#import "MoreViewController.h"
//#import "Bird.h" //maybe delete
#import "BirdInfo.h"
#import "BirdImage.h"
#import "Favorite.h"
#import <CoreData/CoreData.h>
#import "APLViewController.h"
#interface AppDelegate () //class extension
#property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, strong) NSManagedObjectModel *managedObjectModel;
#property (nonatomic, strong) NSPersistentStoreCoordinator *persistentStoreCoordinator;
#property (nonatomic, strong) NSArray *fetchedObjects;
#end
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
UINavigationController *naviController = (UINavigationController *)tabBarController.viewControllers[0];
naviController = (UINavigationController *)tabBarController.viewControllers[0];
BirdsTableViewController *catalogViewController = (BirdsTableViewController *)[naviController topViewController];
// catalogViewController.managedojbectContext = self.managedObjectContext;
//pass managed context to species view controller
naviController = (UINavigationController *)tabBarController.viewControllers[0];
MapViewController *mapViewController = (MapViewController *)[naviController topViewController];
mapViewController.managedOjbectContext = self.managedObjectContext;
naviController = (UINavigationController *)tabBarController.viewControllers[0];
FavoriteTableViewController *favoriteViewcontroller = (FavoriteTableViewController *)[naviController topViewController];
favoriteViewcontroller.managedOjbectContext = self.managedObjectContext;
//pass managed context view controller
naviController = (UINavigationController *)tabBarController.viewControllers[0];
APLViewController *aplViewController = (APLViewController *)[naviController topViewController];
aplViewController.managedOjbectContext = self.managedObjectContext;
/*
//[self preloadData]; //preload birds info into core data
// UITabBarController *tabBarController ;
UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
//pass managed context to first view controller
UINavigationController *naviController = (UINavigationController *)tabBarController.viewControllers[0];
BirdsTableViewController *birdsTableViewController = (BirdsTableViewController *)[naviController topViewController];
birdsTableViewController.managedOjbectContext = self.managedObjectContext;
//pass managed context to nearby view controller
naviController = (UINavigationController *)tabBarController.viewControllers[1];
GeneralViewController *generalViewController = (GeneralViewController *)[naviController topViewController];
generalViewController.managedOjbectContext = self.managedObjectContext;
//pass managed context to species view controller
naviController = (UINavigationController *)tabBarController.viewControllers[2];
SpeciesViewController *catalogViewController = (SpeciesViewController *)[naviController topViewController];
catalogViewController.managedOjbectContext = self.managedObjectContext;
//pass managed context to favorite view controller
naviController = (UINavigationController *)tabBarController.viewControllers[3];
FavoritesViewController *favoriteViewcontroller = (FavoritesViewController *)[naviController topViewController];
favoriteViewcontroller.managedOjbectContext = self.managedObjectContext;
UIColor* navColor = [UIColor colorWithRed:0.175f green:0.458f blue:0.831f alpha:1.0f];
[[UINavigationBar appearance] setBarTintColor:navColor];
[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
[[UINavigationBar appearance] setTitleTextAttributes:#{NSForegroundColorAttributeName: [UIColor whiteColor]}];
//UIColor *barColor = [UIColor colorWithRed:0.012 green:0.286 blue:0.553 alpha:1.0];
[tabBarController.tabBar setTintColor:navColor];
//[self preLoadSpecies];
[AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
//set tab bar item selected images;
NSArray *array = tabBarController.tabBar.items;
((UITabBarItem *)array[2]).selectedImage = [UIImage imageNamed:#"Pelican Filled"];
((UITabBarItem *)array[0]).selectedImage = [UIImage imageNamed:#"Log Cabin Filled"];
((UITabBarItem *)array[1]).selectedImage = [UIImage imageNamed:#"Binoculars Filled"];
((UITabBarItem *)array[3]).selectedImage = [UIImage imageNamed:#"Like Filled"];
//pass managed context to general view controller
UINavigationController *naviController = (UINavigationController *)tabBarController.viewControllers[0];
GeneralViewController *Genralviewcontroler = (GeneralViewController *)[naviController topViewController];
Genralviewcontroler.managedOjbectContext = self.managedObjectContext;
[window addSubview:_navController.view];
*/
//set tab bar item selected images;
NSArray *array = tabBarController.tabBar.items;
//((UITabBarItem *)array[2]).selectedImage = [UIImage imageNamed:#"Pelican Filled"];
((UITabBarItem *)array[0]).selectedImage = [UIImage imageNamed:#"Log Cabin Filled"];
//((UITabBarItem *)array[1]).selectedImage = [UIImage imageNamed:#"Falcon Filled"];
((UITabBarItem *)array[2]).selectedImage = [UIImage imageNamed:#"Like Filled"];
return YES;
}
- (void)applicationWillTerminate:(UIApplication *)application {
}
#pragma mark - Core Data stack
- (NSManagedObjectModel *)managedObjectModel
{
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *uModelURL = [[NSBundle mainBundle] URLForResource:#"Locations" withExtension:#"momd"];
NSManagedObjectModel* uModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:uModelURL];
NSURL *pdModelURL = [[NSBundle mainBundle] URLForResource:#"TaxonModel" withExtension:#"mom"];
NSManagedObjectModel* pdModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:pdModelURL];
_managedObjectModel = [NSManagedObjectModel modelByMergingModels:[NSArray arrayWithObjects:uModel, pdModel, nil]];
return _managedObjectModel;
}
- (NSString *)documentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths lastObject];
//NSLog(#"document directory: %#", documentsDirectory);
return documentsDirectory;
}
- (NSString *)dataStorePath
{
return [[self documentsDirectory] stringByAppendingPathComponent:#"DataStore.sqlite"];
}
/**
Returns the persistent store coordinator for the application.
If the coordinator doesn't already exist, it is created and the application's store added to it.
*/
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
[self addSeedDataToCoordinator:_persistentStoreCoordinator];
NSURL* userURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"UserData.sqlite"];
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
/*
// Allow inferred migration from the original version of the application.
NSDictionary *options = #{ NSMigratePersistentStoresAutomaticallyOption : #YES, NSInferMappingModelAutomaticallyOption : #YES };
*/
// Note that we use our UserConf here
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:#"UserConf" URL:userURL options:nil error:&error])
{
NSLog(#"Error %#",error);
}
[self addSkipBackupAttributeToItemAtPath:[self dataStorePath]]; // *******i added*******
return _persistentStoreCoordinator;
}
- (void) addSeedDataToCoordinator:(NSPersistentStoreCoordinator *)storeCoordinator
{
// Our destination url, writtable. Make sure this is in Library/Cache if you don't want iCloud to backup this.
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"DataStore.sqlite"];
NSError *error = nil; //************ i define
//NSURL* adURL;//********************i define
// If we don't have our migrated store, prepare it
if (![[NSFileManager defaultManager] fileExistsAtPath:[storeURL path]])
{
// Our source url should come from a download, but let's use our bundle for debug purposes in the simulator
NSURL *baseURL = [[NSBundle mainBundle] URLForResource:#"DataStore" withExtension:#"sqlite"];
// [[NSFileManager defaultManager] copyItemAtPath:baseURL toPath:[self dataStorePath] error:NULL]; ///##########this line
// [NSFileManager defaultManager]copyItemAtPath:<#(nonnull NSString *)#> toPath:<#(nonnull NSString *)#> error:NULL];
[[NSFileManager defaultManager]contentsAtPath:[self dataStorePath]]; // I ADD THIS LINE
// Create one coordinator that just migrates, but isn't used.
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
nil];
// This will just handle the migration, without any configuration or else ...
NSPersistentStore* tmpStore = [storeCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error];
// And remove it !
[storeCoordinator removePersistentStore:tmpStore error:&error];
}
// And now add the coordinator with the correct 'PostCodesConf' configuration, in readonly mode
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSReadOnlyPersistentStoreOption, nil];
[storeCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:#"PostCodesConf" URL:storeURL options:options error:&error];
}
- (BOOL)addSkipBackupAttributeToItemAtPath:(NSString *) filePathString
{
NSURL* URL= [NSURL fileURLWithPath:filePathString];
assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
NSError *error = nil;
BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
forKey: NSURLIsExcludedFromBackupKey error: &error];
if(!success){
NSLog(#"Error excluding %# from backup %#", [URL lastPathComponent], error);
}
//NSLog(#"Added %#",[NSNumber numberWithBool: success]);
return success;
}
- (NSManagedObjectContext *)managedObjectContext
{
if (_managedObjectContext == nil) {
NSPersistentStoreCoordinator *coordinator = self.persistentStoreCoordinator;
if (coordinator !=nil) {
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
}
return _managedObjectContext;
}
- (void)preloadData {
NSString *path = [[NSBundle mainBundle] pathForResource:#"acachecklist" ofType:#"txt"];
NSError *error;
NSString *allBirds = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
if (allBirds == nil) {
//NSLog(#"Error reading file: %#",[error localizedDescription]);
}
NSArray *lines=[allBirds componentsSeparatedByString:#"\n"];
unsigned long count = [lines count];
NSArray *bird;
for(int i=0;i<count;i++) {
bird=[[lines objectAtIndex:i] componentsSeparatedByString:#"\t"];
BirdInfo *info = [NSEntityDescription insertNewObjectForEntityForName:#"BirdInfo"
inManagedObjectContext:self.managedObjectContext];
BirdImage *imageObj = [NSEntityDescription insertNewObjectForEntityForName:#"BirdImage"
inManagedObjectContext:self.managedObjectContext];
UIImage *tempImage = [UIImage imageNamed:#"Placeholder"];
imageObj.image = UIImageJPEGRepresentation(tempImage,1);
info.category = [bird objectAtIndex:0];
info.com_name = [bird objectAtIndex:1];
info.sci_name = [bird objectAtIndex:2];
//info.taxon_id = [bird objectAtIndex:2];
info.thumbnailImage = imageObj;
NSError *error;
if (![self.managedObjectContext save:&error]) {
//NSLog(#"Error: %#", error);
abort();
}
}
}
- (void)preLoadSpecies
{
NSManagedObjectContext *privateContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
privateContext.persistentStoreCoordinator = self.managedObjectContext.persistentStoreCoordinator;
NSEntityDescription *entity = [NSEntityDescription insertNewObjectForEntityForName:#"BirdInfo"
inManagedObjectContext:self.managedObjectContext];
NSFetchRequest *allSpeciesRequest = [[NSFetchRequest alloc] init];
[allSpeciesRequest setEntity:entity];
[privateContext performBlock:^{
NSError *error;
self.fetchedObjects = [privateContext executeFetchRequest:allSpeciesRequest error:&error];
if (error) {
//NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}];
}
// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
#end
App crashes when I want to load data in first view controller with below logs:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'BirdInfo''
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Hi i am beginner in Ios and in my project i have given facility for users capturing photos and videos and Audios from camera and i am storing their "paths" in array lists and i am displays them in one table-list so for everything is ok
But here my main requirement is when i click table-list rows then if there is image file it must be shows or if there is video it must be play audio also have to play as like videos for this i have written some code here photos and videos are playing fine but audio files giving problem what did i do here wrong?
my code:-
#import "ViewController2.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
#interface ViewController2 ()
{
NSMutableArray * arr_mediaType;
UIImagePickerController *imagePicker;
UIImage *snap;
NSData *data1;
NSMutableArray * arr_media;
MPMoviePlayerController * moviePlayer;
UIImageView *dot;
AVAudioRecorder * _audioRecorder;
AVAudioPlayer * player;
}
#end
#implementation ViewController2
#synthesize maintablelist;
- (void)viewDidLoad {
arr_mediaType = [[NSMutableArray alloc]init];
arr_media = [[NSMutableArray alloc]init];
maintablelist.delegate = self;
maintablelist.dataSource = self;
[super viewDidLoad];
}
- (IBAction)takePicture:(id)sender {
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeImage, nil];
[self presentViewController:imagePicker animated:NO completion:nil];
}
- (IBAction)takeVideo:(id)sender {
NSString *model = [[UIDevice currentDevice] model];
if ([model isEqualToString:#"iPhone Simulator"] || [model isEqualToString:#"iPad Simulator"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Angry!!!" message:#"No Camera found!" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
else
{
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.videoMaximumDuration = 10;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];
[self presentViewController:imagePicker animated:NO completion:nil];
}
}
- (IBAction)takeAudio:(id)sender {
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString]; // to get unique name
NSString *soundfile = [NSString stringWithFormat:#"sound%#.m4a",fileName];
NSString *soundFilePath = [docsDir
stringByAppendingPathComponent:soundfile];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSLog(#"FilePath:%#",soundFileURL);
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
NSError *error = nil;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord
error:nil];
_audioRecorder = [[AVAudioRecorder alloc]
initWithURL:soundFileURL
settings:recordSetting
error:&error];
if (error)
{
NSLog(#"error: %#", [error localizedDescription]);
}
else {
NSLog(#"ok");
[arr_media addObject:soundFilePath];
[_audioRecorder record];
[maintablelist reloadData];
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:#"public.image"]){
[mediaType isEqual: #"Photos"];
[arr_mediaType addObject:#"Photos"];
snap = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString];
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:#"Pic-%#.png", fileName]];
NSData *data = UIImageJPEGRepresentation(snap, 1.0);
[data writeToFile:filePath atomically:YES];
[picker dismissViewControllerAnimated:YES completion:nil];
NSLog(#"So finally path is%#",filePath);
[arr_media addObject:filePath];
[maintablelist reloadData];
}
else {
[mediaType isEqual: #"Videos"];
[arr_mediaType addObject:#"Video"];
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"videoURL --->>> %#",videoURL);
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString];
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:#"video%#.mov", fileName]];
BOOL success = [videoData writeToFile:filePath atomically:NO];
[arr_media addObject:filePath];
NSLog(#"videoURLPath --->>> %#",filePath);
[picker dismissViewControllerAnimated:YES completion:nil];
[maintablelist reloadData];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arr_mediaType.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *cells=#"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:nil];
if (cell==nil) {
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cells];
}
cell.textLabel.text = [arr_media objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([[arr_mediaType objectAtIndex:indexPath.row] isEqualToString:#"Photos"]) {
[moviePlayer.view removeFromSuperview];
dot =[[UIImageView alloc] initWithFrame:CGRectMake(40,320,240,128)];
dot.image = [UIImage imageNamed:[arr_media objectAtIndex:indexPath.row]];
[self.view addSubview:dot];
}
else if([[arr_mediaType objectAtIndex:indexPath.row] isEqualToString:#"Videos"])
{
[dot removeFromSuperview];
NSURL*theurl=[NSURL fileURLWithPath:[arr_media objectAtIndex:indexPath.row]];
moviePlayer=[[MPMoviePlayerController alloc] initWithContentURL:theurl];
[moviePlayer.view setFrame:CGRectMake(40, 320, 240, 128)];
[moviePlayer prepareToPlay];
[moviePlayer setShouldAutoplay:NO];
[self.view addSubview:moviePlayer.view];
}
else
{
NSString *filePath = [arr_media objectAtIndex:indexPath.row];
NSData *soundData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:filePath]];
player = [[AVAudioPlayer alloc] initWithData:soundData error:nil];
[player setDelegate:self];
[player play];
}
}
#end
Here, I have modified your piece of code. First of all, there is no need of different arrays to store images and videos. You can access it from one. Simillarly, there is no need of storing media types in two different arrays. You can do it by one array.
Moreover, to save images and videos to document directory, you need to write those file to specific path. You will then be able to access them.
#import "ViewController.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import <MediaPlayer/MediaPlayer.h>
#interface ViewController ()
{
NSMutableArray * arr_mediaType;
UIImagePickerController *imagePicker;
UIImage *snap;
NSData *data1;
NSMutableArray * arr_media;
MPMoviePlayerController * moviePlayer;
UIImageView *dot;
}
#end
#implementation ViewController
#synthesize tbl;
- (void)viewDidLoad {
arr_mediaType = [[NSMutableArray alloc]init];
arr_media = [[NSMutableArray alloc]init];
tbl.delegate = self;
tbl.dataSource = self;
[super viewDidLoad];
}
- (IBAction)takePicture:(id)sender {
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeImage, nil];
[self presentViewController:imagePicker animated:NO completion:nil];
}
- (IBAction)takeVideo:(id)sender {
NSString *model = [[UIDevice currentDevice] model];
if ([model isEqualToString:#"iPhone Simulator"] || [model isEqualToString:#"iPad Simulator"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Angry!!!" message:#"No Camera found!" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
else
{
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.videoMaximumDuration = 10;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];
[self presentViewController:imagePicker animated:NO completion:nil];
}
}
-(IBAction)takeAudio
{
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString]; // to get unique name
NSString *soundfile = [NSString stringWithFormat:#"sound%#.m4a",fileName];
NSString *soundFilePath = [docsDir
stringByAppendingPathComponent:soundfile];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSLog(#"FilePath:%#",soundFileURL);
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
NSError *error = nil;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord
error:nil];
_audioRecorder = [[AVAudioRecorder alloc]
initWithURL:soundFileURL
settings:recordSettings
error:&error];
if (error)
{
NSLog(#"error: %#", [error localizedDescription]);
} else {
[arr_media addObject:soundFilePath];
[_audioRecorder record];
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:#"public.image"]){
[mediaType isEqual: #"Photos"];
[arr_mediaType addObject:#"Photos"];
snap = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString];
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:#"Pic-%#.png", fileName]];
NSData *data = UIImageJPEGRepresentation(snap, 1.0);
[data writeToFile:filePath atomically:YES];
[picker dismissViewControllerAnimated:YES completion:nil];
//UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//
// NSString *Dir = [paths objectAtIndex:0];
// NSString *fileName = [NSString stringWithFormat:#"Pic-%lf.png", [[NSDate date] timeIntervalSince1970]];
//
// //this path if you want save reference path in sqlite
// NSString *pngPath = [NSString stringWithFormat:#"%#/%#",Dir,fileName];
//
NSLog(#"So finally path is%#",filePath);
[arr_media addObject:filePath];
[tbl reloadData];
}
else {
[mediaType isEqual: #"Videos"];
[arr_mediaType addObject:#"Video"];
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"videoURL --->>> %#",videoURL);
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString];
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:#"video%#.mov", fileName]];
BOOL success = [videoData writeToFile:filePath atomically:NO];
[arr_media addObject:filePath];
NSLog(#"videoURLPath --->>> %#",filePath);
[picker dismissViewControllerAnimated:YES completion:nil];
[tbl reloadData];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arr_mediaType.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *cells=#"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:nil];
if (cell==nil) {
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cells];
}
cell.textLabel.text = [arr_media objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([[arr_mediaType objectAtIndex:indexPath.row] isEqualToString:#"Photos"]) {
[moviePlayer.view removeFromSuperview];
dot =[[UIImageView alloc] initWithFrame:CGRectMake(40,320,240,128)];
dot.image = [UIImage imageNamed:[arr_media objectAtIndex:indexPath.row]];
[self.view addSubview:dot];
}
else if([[arr_mediaType objectAtIndex:indexPath.row] isEqualToString:#"Videos"])
{
[dot removeFromSuperview];
// NSString*thePath=[[NSBundle mainBundle] pathForResource:[arr_media objectAtIndex:indexPath.row] ofType:#"MOV"];
NSURL*theurl=[NSURL fileURLWithPath:[arr_media objectAtIndex:indexPath.row]];
moviePlayer=[[MPMoviePlayerController alloc] initWithContentURL:theurl];
[moviePlayer.view setFrame:CGRectMake(40, 320, 240, 128)];
[moviePlayer prepareToPlay];
[moviePlayer setShouldAutoplay:NO];
[self.view addSubview:moviePlayer.view];
}
else
{
NSString *filePath = [arr_media objectAtIndex:indexPath.row];
NSData *soundData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:filePath]];
player = [[AVAudioPlayer alloc] initWithData:soundData error:nil];
[player setDelegate:self];
[player play];
}
#end
Your issue is that you are not saving the captured images/photos and simply trying to use the paths. Please take a look at Apple Documentation on how to use it. You can save them in your project's Documents directory, save the file name and path as you are doing then use those paths for rendering/playing later on.
As a side note, in your implementation, there are few lines of code that you are executing after [picker dismissViewControllerAnimated:YES completion:nil]. I would advise to utilize completion block here and load your table view once image picker view dismissal is complete. This avoid run time crashes.
EDIT: On OP request
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage])
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory, #“image1.png”];
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImageJPEGRepresentation(image, 1);
[imageData writeToFile: filePath atomically:YES];
[picker dismissViewControllerAnimated:YES completion:^{
// Save your model data and reload table here
}];
}
}
I'm trying to preview a downloaded file to system and the program crashes when performing the method called previewController:previewItemAtIndex:. From what I assumed is that is releasing the previewcontroller before it is displayed, but this error does not occur when the file is already in the documents folder. It only happens when trying to open the file right after it has been downloaded.
Here is the code:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
NSUInteger count = [listSessionsST count];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
Signature *object = [listSessionsST objectAtIndex:row];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UILabel *lblInComplete = (UILabel*)[cell viewWithTag:4];
UIImageView *imgCheck = (UIImageView*)[cell viewWithTag:3];
//Sets the File Name
self.File = [[[NSString stringWithFormat:#"%#_%#.%#",object.FileName,object.ModDate,object.Extension]
componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString: #""];
//Shows the loading screen while the file is being downloaded
[DejalBezelActivityView activityViewForView:self.view withLabel:#"Downloading" width:0 LoadingType:#"Full"];
[DejalActivityView currentActivityView].showNetworkActivityIndicator = YES;
//Calls the method that will begin downloading the file
[self performSelector:#selector(startDownload:) withObject:object.Location afterDelay:0.2];
}
- (void)startDownload:(NSString *)strLocation{
NSString *filePath = [NSString stringWithFormat:#"%#/tmp/%#", NSHomeDirectory(),self.File];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
if (fileExists)
{
[DejalBezelActivityView removeViewAnimated:YES];
//QuickLook APIs directly to preview the document
QLPreviewController *previewController = [[QLPreviewController alloc] init];
previewController.dataSource = self;
previewController.delegate = self;
[[self navigationController] pushViewController:previewController animated:YES];
[previewController release];
}
else
{
NSDictionary *dictionary = [Signature downloadFile:self.File Path:strLocation];
if ([dictionary valueForKey:#"Error"] == nil)
{
//If no error has occurred while downloading then preview the file.
//QuickLook APIs directly to preview the document
QLPreviewController *previewController = [[QLPreviewController alloc] init];
previewController.dataSource = self;
previewController.delegate = self;
[[self navigationController] pushViewController:previewController animated:YES];
[previewController release];
[DejalBezelActivityView removeViewAnimated:YES];
}
else
{
//If an error occurred while downloading then display message to user.
[DejalBezelActivityView removeViewAnimated:YES];
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#""
message:[dictionary valueForKey:#"Response"]
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alert show];
[alert release];
}
}
}
// Returns the number of items that the preview controller should preview
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)previewController{
return 1;
}
// returns the item that the preview controller should preview
- (id)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index{
NSString *path = [NSString stringWithFormat:#"%#/tmp/%#", NSHomeDirectory(),self.File];
return [NSURL fileURLWithPath:path];
}
The method that downloads the file and saves it to the tmp folder
---------------------------------------------------------------
+ (NSDictionary *)downloadFile:(NSString *)strFile Path:(NSString *)strPath{
float freeSpace = 0.0f;
NSError *error = nil;
NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[NSString stringWithFormat:#"%#/tmp", NSHomeDirectory()]
error: &error];
if (dictionary)
{
NSNumber *fileSystemFreeSizeInBytes = [dictionary objectForKey: NSFileSystemFreeSize];
freeSpace = [fileSystemFreeSizeInBytes floatValue];
}
else
{
//Handle error
NSLog(#"Error;%#",error);
return [NSDictionary dictionaryWithObjectsAndKeys:#"An error has occurred while downloading the file.",#"Response",#"Y",#"Error", nil];
}
if (freeSpace > 0.0f)
{
NSDictionary *dict = nil;
BOOL blnHasErroroccurred = NO;
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *encoded = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)strPath,
NULL,
(CFStringRef)#"!*'\"();:#&=+$,/?%#[]%",
kCFStringEncodingUTF8 );
NSString *strURL = [NSString stringWithFormat:#"%#/DataTransfer/DownloadFile?EMP_ID=%#&FilePath=%#",
appDelegate.ServerAddress,
appDelegate.UserId,
encoded];
[encoded release];
NSURL *url = [NSURL URLWithString:strURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy: NSURLRequestUseProtocolCachePolicy
timeoutInterval:20.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSURLResponse* response = nil;
NSError* resultError = nil;
NSData* dataResult = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&resultError];
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
if ([httpResponse statusCode] == 200)
{
#try
{
if (dataResult.length < freeSpace)
{
//Get the tmp directory
NSFileManager *fileManager =[NSFileManager defaultManager];
NSString *fileName = [NSString stringWithFormat:#"%#/tmp/%#", NSHomeDirectory(),strFile];
//Write the data to using the tmp directory
BOOL filecreationSuccess = [fileManager createFileAtPath:fileName contents:dataResult attributes:nil];
if(filecreationSuccess == YES)
{
dict = [NSDictionary dictionaryWithObjectsAndKeys:#"",#"Response",nil,#"Error", nil];
}
else
{
blnHasErroroccurred = YES;
}
}
}
#catch (NSException *exception)
{
blnHasErroroccurred = YES;
}
}
else
{
blnHasErroroccurred = YES;
}
if(blnHasErroroccurred == YES)
{
dict = [NSDictionary dictionaryWithObjectsAndKeys:#"An error has occurred while downloading the file.", #"Response", #"Yes",#"Error",nil];
}
[dataResult release];
return dict;
}
else
{
return [NSDictionary dictionaryWithObjectsAndKeys:#"Not enough disk space to download file.",#"Response",#"Y",#"Error", nil];
}
}
I am new to ios programming so forgive me for mistakes.
I am developing an app which requires uploading and downloading files basically image files.I am using AWS ios sdk.I am able to download the image file and save it to Document folder(while testing on simulator).
The problem is once the image gets downloaded i have to move it to photo library of iphone.The code is :-
-(IBAction)downloadButtonAction:(id)sender;
{
NSMutableArray *rowsToBeDownloaded = [[NSMutableArray alloc] init];
NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
int index = 0;
for (NSNumber *rowSelected in selectedArray)
{
if ([rowSelected boolValue])
{
[rowsToBeDownloaded addObject:[objects objectAtIndex:index]];
NSUInteger pathSource[2] = {0, index};
NSIndexPath *path = [NSIndexPath indexPathWithIndexes:pathSource length:2];
[indexPaths addObject:path];
}
index++;
}
if([rowsToBeDownloaded count]==0)
{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Alert" message:#"Please select a file to download" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
for (id value in rowsToBeDownloaded)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:value];
AmazonS3Client *s3Client = [[AmazonS3Client alloc] initWithAccessKey:accessKey withSecretKey:secretKey];
NSOutputStream *stream = [[NSOutputStream alloc] initToFileAtPath:path append:NO];
[stream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[stream open];
S3GetObjectRequest *request = [[S3GetObjectRequest alloc] initWithKey:value withBucket:self.bucket];
request.outputStream = stream;
[s3Client getObject:request];
//UIImageWriteToSavedPhotosAlbum(self.selectedImage, nil,nil,nil);
[stream close];
[stream release];
[request release];
}
}
[indexPaths release];
[rowsToBeDeleted release];
[self populateSelectedArray];
[self transferImagesToPhotolibrary];
}
-(void)transferImagesToPhotolibrary
{
//int index=0;
//
// NSMutableArray*imgArr=[[NSMutableArray alloc] init];
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *documentsDirectory = [paths objectAtIndex:0];
// NSDirectoryEnumerator *directoryEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:documentsDirectory];
//
//
// for (NSString *path in directoryEnumerator)
// {
// if([[path pathExtension]isEqualToString:#"png"])
// {
// [imgArr addObject:path];
// //UIImage*img=[UIImage imageNamed:path];
// //UIImageWriteToSavedPhotosAlbum(img, nil,nil,nil);
//
// }
// }
NSMutableArray*imgArr=[[NSMutableArray alloc] init];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSDirectoryEnumerator *directoryEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:documentsDirectory];
for (NSString *path in directoryEnumerator)
{
if([[path pathExtension]isEqualToString:#"png"])
{
printf("\n path is %s",[path UTF8String]);
[imgArr addObject:path];
}
}
for(int i=0;i<[imgArr count];i++)
{
UIImage*img=[UIImage imageNamed:[imgArr objectAtindex:i]];
UIImageWriteToSavedPhotosAlbum(img, nil,nil,nil);
}
}
I tried many ways to achieve it but was unable to do it.
The image Array contains the names of the image but I am not able to access those images.
I tried displaying the image in image view also but it's not appering there also..
Please help.
Thanks.
And finally I was able to solve this problem.Here is the code for the people in need.
AmazonS3Client *s3Client = [[AmazonS3Client alloc] initWithAccessKey:accessKey withSecretKey:secretKey];
NSOutputStream *stream = [[NSOutputStream alloc] initToFileAtPath:path append:NO];
[stream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[stream open];
S3GetObjectRequest *request = [[S3GetObjectRequest alloc] initWithKey:value withBucket:self.bucket];
request.outputStream = stream;
[s3Client getObject:request];
// NSMutableArray*imgArr=[[NSMutableArray alloc] init];
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:value];
NSData *myData = [[[NSData alloc] initWithContentsOfFile:appFile] autorelease];
UIImage *img=[UIImage imageWithData:myData];
UIImageWriteToSavedPhotosAlbum(img, nil,nil,nil);
[stream close];
[stream release];
[request release];
}