I'm using FMDB in my project, I constructed the first sqlite3 database in terminal, and loaded it into my project. Later I made some changes to that database, so I deleted it from project (move to trash), and "add files" again. But the running result seems still accord to the previous database or sometimes just no query result. I also tried to remove the database and run project, it's still running with no error... Additionally, I imported a newer database with another name, it can't work either. So is there anything additional I need to do to totally remove a database in objective-c and reload one? Thanks!
My code shows as below:
- (IBAction)submitButton:(id)sender {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"finalCarpool.db"];
FMDatabase* db = [FMDatabase databaseWithPath:writableDBPath];
NSLog(#"Is SQLite compiled with it's thread safe options turned on? %#!", [FMDatabase isSQLiteThreadSafe] ? #"Yes" : #"No");
if (![db open]) {
NSLog(#"Could not open db.");
}
FMResultSet *rs = [db executeQuery:#"select * from userinfo"];
int count=0;
while ([rs next]) {
count++;
NSLog(#"%i",count);
}
FMResultSet *rs2 = [db executeQuery:#"select id from userinfo where username = ? AND password= ?", usernameTextField.text,passwordTextField.text];
if ([rs2 next]) {
NSString *welcomeMessage=[[NSString alloc]initWithFormat:#"Welcome, %#",usernameTextField.text];
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:#"Successfully Login!"
message:welcomeMessage
delegate:nil
cancelButtonTitle:#"Okay"
otherButtonTitles:nil];
[myAlert show];
[self.loginDelegate backToLaunch];
}
else {
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:#"Something is wrong..."
message:#"Your username and/or password doesn't match!Please try again!"
delegate:nil
cancelButtonTitle:#"Okay"
otherButtonTitles:nil];
[myAlert show];
usernameTextField.text=Nil;
passwordTextField.text=Nil;
}
[usernameTextField resignFirstResponder];
[passwordTextField resignFirstResponder];
}
If you are testing on the simulator, the database path is
~/Library/Application Support/iPhone Simulator/<SIMULATOR-VERSION>/Applications/<APP-NAME>/Documents/finalCarpool.db
You can delete it from there.
Otherwise you can just delete the application from the simulator (in the same way you would do from the iPhone).
Go TO Ios Simulator> ResetContent and setting
Related
I have tried various google searches that landed on examples here and none seem to work right for one of my specific copy routines.
I am attempting to have a backup and restore option for an outside program in a helper program I am designing.
I tried NSURL and associated array and loops to iterate through dir contents.
I have tried the escaped space in the path string and url.
I have also tried as the examples below show, to do just a raw file copy based on a path NSString.
Swift is not really an option for me so I am mainly trying to go the route of objective-c.
This section works:
- (void)backup
{
NSString *userFiles = #"~/Library/Application Support/OutsideProgramHere/";
userFiles = [userFiles stringByExpandingTildeInPath];
NSString *backup = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"backup"];
[[NSFileManager defaultManager] copyItemAtPath:userFiles toPath:backup error:nil];
NSString *bothpaths = [NSString stringWithFormat:#"Copied\r\n\r\nUser Path:%#\r\n\r\n<to>\r\n\r\nBackup Path:%#", userFiles, backup];
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:bothpaths];
[alert addButtonWithTitle:#"OK"];
[alert setAlertStyle:NSWarningAlertStyle];
[alert runModal];
}
The reverse does not:
- (void)restore
{
NSString *userFiles = #"~/Library/";
userFiles = [userFiles stringByExpandingTildeInPath];
userFiles = [NSString stringWithFormat:#"%#/Application Support/OutsideProgramHere",userFiles];
NSString *backup = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"backup"];
//backup = [NSString stringWithFormat:#"%#/", backup];
[[NSFileManager defaultManager] copyItemAtPath:backup toPath:userFiles error:nil];
NSString *bothpaths = [NSString stringWithFormat:#"Copied\r\n\r\nBackup Path:%#\r\n\r\n<to>\r\n\r\nUser Path:%#", backup, userFiles];
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:bothpaths];
[alert addButtonWithTitle:#"OK"];
[alert setAlertStyle:NSWarningAlertStyle];
[alert runModal];
}
As you can see I tried to mess with the path a little bit as well.
I originally created the path output message as a debug, but I think that will remain as a confirmation to the user on success.
It also is intentional that it saves backups to this program's package/resources folder.
The source folder will have files and folders inside it together that it should copy over recursively keeping structure in tact.
I am kinda at a loss as to how to go from here without drastically changing any other aspects of the code. I can see how this "may" duplicate questions asked before. But as I said, no other examples I have found work, and looking for only objective-c solutions.
Self discovered answer:
[[NSFileManager defaultManager] removeItemAtPath:userFiles error:nil];
before the copy works.
I'm building an app that is using the Instagram API to display photos but I'm running into some trouble. The app is crashing when there is no network connection and I have found the code that is causing the problem.
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
self.accessToken = [userDefaults objectForKey:#"accessToken"];
if (self.accessToken == nil) {
[SimpleAuth authorize:#"instagram" options:#{#"scope": #[#"likes"]} completion:^(NSDictionary *responseObject, NSError *error) {
self.accessToken = responseObject[#"credentials"][#"token"];
[userDefaults setObject:self.accessToken forKey:#"accessToken"];
[userDefaults synchronize];
[self refresh];
}];
} else {
[self refresh];
}
I have found that the [self refresh]; is causing the problem in the else block and I tried to replace it with a alert view like this
UIAlertView *networkError = [[UIAlertView alloc] initWithTitle:#"Network Error" message:#"Please connect your device to a network and restart application" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
[networkError show];
However, with this problem I find that if I open the app with a network connection I still get the alert. Any help would be great because I'm still new to Objective C!
Thank you for the help!
I know this code from Treehouse :).
The thing is that the if (self.accessToken == nil) { /.../ } block will only get execute when the app is not authorized using your Instagram credentials.
Once you logged in successfully, it will always execute the code in the else { /.../ } block. If it has connection to Internet, it will do its work, download, display images etc. If you insert the code to display alert, it will always do that because you actually mean that by that code.
If you want to check if there is some connection, you need to do that before all that code, display an error and return instantly if connection is not available. However, the author tried to keep things simple, assuming there is always Internet connection.
Hope it makes you understand it.
This is the some code you can use for checking if there is connection:
// show some activity indicator
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
// Do something...
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
NSURL *url = [NSURL URLWithString:#"http://www.apple.com/"];
NSString *s = [NSString stringWithContentsOfURL:url
encoding:NSUTF8StringEncoding
error:nil];
dispatch_async(dispatch_get_main_queue(), ^{
// hide the activity indicator
self.connected = (s != nil);
[[UIApplication sharedApplication] endIgnoringInteractionEvents];
if (self.isConnected)
{
NSLog(#"self.connected == YES");
}
else
{
NSLog(#"self.connected == NO");
NSString *alertMessage = #"In order to load images, you need an active Internet connection. Please try again later!";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Sorry!"
message:alertMessage
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
});
});
You obviously need to add a property to you class. You can insert this code:
#interface LDPhotosViewController ()
#property (nonatomic, copy, getter = isConnected) NSString *connected;
#end
at the top of LDPhotosViewController.m file, before the #implementation line.
There are some questions I have found but the answers don't work with my code, therefore I ask a question of my own.
My objective is reloading a table view from a detailviewcontroller. I tap a cell, go to the detail and when I return to the table I want it updated. The thing is it doesn't update. So I decided it would be better to go back to the rootviewcontroller when certain thing happens on the detailviewcontroller but it still didn't work.
I am open to suggestions and advice feel free to comment!!
I download a video and when the video is downloaded I update the tableView.
Here is the code I am using:
I use MKNetworkKit btw.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *cachesDirectory = [paths objectAtIndex:0];
NSString *downloadPath = [cachesDirectory stringByAppendingPathComponent:videoName];
self.downloadOperation = [ApplicationDelegate.mainDownloader downloadVideoFrom:finalAddress
toFile:downloadPath];
[self.downloadOperation onDownloadProgressChanged:^(double progress) {
//DLog(#"%.2f", progress*100.0);
//self.downloadProgressBar.progress = progress;
}];
[self.downloadOperation onCompletion:^(MKNetworkOperation* completedRequest) {
//THIS DOES NOT WORK, dismissModalViewControllerAnimated.
[[ApplicationDelegate.window rootViewController] dismissModalViewControllerAnimated:YES];
DLog(#"COMPLETED REQUEST: %#", completedRequest);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Download completed"
message:#"The file is in your photo and video Library"
delegate:nil
cancelButtonTitle:NSLocalizedString(#"Thank you WebSurg!!", #"")
otherButtonTitles:nil];
[alert show];
// THIS IS WHAT I PREVIOUSLY TRIED.
// NSDictionary *tableSecData = ApplicationDelegate.videoLibraryController.tableSectionData;
// NSMutableArray *tempValuesDownloaded = [tableSecData objectForKey:#"Downloaded videos"];
// NSMutableArray *tempValuesUndownloaded = [tableSecData objectForKey:#"Undownloaded videos"];
// for (NSArray *videoArray in tempValuesUndownloaded) {
// if ([[videoArray objectAtIndex:0] isEqualToString:self.videoDetailTitle.text]) {
// [tempValuesUndownloaded removeObject:videoArray];
// [tempValuesDownloaded addObject:videoArray];
// }
// }
// [ApplicationDelegate.videoLibraryController.tableSectionData removeAllObjects];
// ApplicationDelegate.videoLibraryController.tableSectionData = [NSMutableDictionary dictionaryWithObjectsAndKeys:tempValuesDownloaded, #"Downloaded videos", tempValuesUndownloaded, #"Undownloaded videos", nil];
// [ApplicationDelegate.videoLibraryController.mainTableView reloadData];
}
onError:^(NSError* error) {
DLog(#"%#", error);
[[[UIAlertView alloc] initWithTitle:#"Download failed" message:#"The download failed because of a connection error please try again" delegate:nil cancelButtonTitle:NSLocalizedString(#"Dismiss", #"") otherButtonTitles:nil] show];
}];
} else {
UIAlertView *failureAlert=[[UIAlertView alloc] initWithTitle:#"Download status" message:#"Download failed, not enough free space." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil, nil];
[failureAlert show];
}
How can I upload a photo to facebook from an iOS app using their new API/SDK? I've already tried and I'm not getting anywhere, just keep running in circles. Here is the code I currently have:
-(void)dataForFaceboo{
self.postParams =
[[NSMutableDictionary alloc] initWithObjectsAndKeys:
self.uploadPhoto.image, #"picture", nil];
}
-(void)uploadToFacebook{
[self dataForFacebook];
NSLog(#"Going to facebook: %#", self.postParams);
// Hide keyboard if showing when button clicked
if ([self.photoCaption isFirstResponder]) {
[self.photoCaption resignFirstResponder];
}
// Add user message parameter if user filled it in
if (![self.photoCaption.text
isEqualToString:kPlaceholderPostMessage] &&
![self.photoCaption.text isEqualToString:#""])
{
[self.postParams setObject:self.photoCaption.text forKey:#"message"];
}
[FBRequestConnection startWithGraphPath:#"me/feed"
parameters:self.postParams
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error)
{
NSString *alertText;
if (error) {
alertText = [NSString stringWithFormat:
#"error: domain = %#, code = %d",
error.domain, error.code];
} else {
alertText = [NSString stringWithFormat:
#"Posted action, id: %#",
[result objectForKey:#"id"]];
}
// Show the result in an alert
[[[UIAlertView alloc] initWithTitle:#"Result"
message:alertText
delegate:self
cancelButtonTitle:#"OK!"
otherButtonTitles:nil] show];
}];
}
Your code is fine, some slight changes to be done:
add the image to the dictionary in NSData format, like
[params setObject:UIImagePNGRepresentation(_image) forKey:#"picture"];
and change the graph path to "me/photos" instead of "me/feed"
Make these changes, it worked for me.
Remember you need to use "publish_actions" permissions.
"me/photos" is meant for the photo actually be in the "Photo's" list on your Facebook profile. "me/feed" is just a post on the timeline.
I have a project that includes FMDB to manage SQLite databases. I imported and linked the FMDB wrappers, but problems is that no results are shown when I query the database :
The sqlite database created with Firefox SQLite manager (Ubuntu) and I copy it to Xcode .
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *path = [docsPath stringByAppendingPathComponent:#"db.sqlite"];
FMDatabase *db = [FMDatabase databaseWithPath:path];
[db open];
FMResultSet *fResult= [db executeQuery:#"SELECT * FROM mytable"];
while([fResult next])
{
NSLog(#"%#",[fResult stringForColumn:#"title"]);
}
[db close];
If you have copied your database into xCode then you should search for your database in your application's main bundle resource path first, then copy it into the Documents directory if it doesn't exist there yet, only then you can work with it. You might want to debug your FMDatabase object using lastErrorMessage and lastErrorCode messages.
FMDatabase *db = [FMDatabase databaseWithPath:path];
NSLog(#"database instantiated: %#", db];
[db open];
NSLog(#"Database has encountered an error with message: %#. And code: %d", db.lastErrorMessage, db.lastErrorCode];
FMResultSet *fResult= [db executeQuery:#"SELECT * FROM mytable"];
while([fResult next])
{
NSLog(#"%#",[fResult stringForColumn:#"title"]);
}
[db close];
The other problem might of course sound silly, but if your 'mytable' does not contain anything, the while loop expression will always be false. But my best guess - the database is not in the Documents directory.