FMDatabase *database = [FMDatabase databaseWithPath:databasePath];
[database open];
FMResultSet *results = nil;
results=[database executeQuery:#"SELECT * FROM CLINIQDB"];
while([results next])
{
countryArr=[[NSMutableArray alloc] init];
[countryArr addObject:[results stringForColumn:#"countryNames"]];
}
NSLog(#"The country arr %#",countryArr);
[database close];
Actually I have 10 country names but contryArr showing only last value for example
my countries are {India,Australia,..........,Russia};
countryArr have only Russia in it.
what's wrong with my code.
Initialise your array before of while loop
FMResultSet *results = nil;
results=[database executeQuery:#"SELECT * FROM CLINIQDB"];
countryArr=[[NSMutableArray alloc] init];
while([results next])
{
[countryArr addObject:[results stringForColumn:#"countryNames"]];
}
NSLog(#"The country arr %#",countryArr);
[database close];
Related
I am developing a chat app which needs contacts for chatting but when first time it is not showing the contacts again restart the app fetch then it is showing here is my code
-(NSMutableArray *)getAllContacts {
sleep(6);
// The user has previously given access, add the contact
ABRecordRef source = ABAddressBookCopyDefaultSource(addressBookRef);
CFArrayRef allPeople = (ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBookRef, source, kABPersonSortByFirstName));
CFIndex nPeople = ABAddressBookGetPersonCount(addressBookRef);
NSMutableArray* items = [[NSMutableArray alloc] init];
if (!allPeople || !nPeople) {
NSLog(#"people nil");
}
CFStringRef description = CFCopyDescription(allPeople);
NSLog(#"Array %#", description);
CFRelease(description);
for (int i = 0; i < nPeople; i++) {
// #autoreleasepool {
//data model
ContactsData *contacts = [ContactsData new];
ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
//get First Name
CFStringRef firstName = (CFStringRef)ABRecordCopyValue(person,kABPersonFirstNameProperty);
contacts.firstNames = (__bridge NSString*)firstName;
if (firstName != NULL) {
CFRelease(firstName);
}
//get Last Name
CFStringRef lastName = (CFStringRef)ABRecordCopyValue(person,kABPersonLastNameProperty);
contacts.lastNames = (__bridge NSString*)lastName;
if (lastName != NULL) {
CFRelease(lastName);
}
if (!contacts.firstNames) {
contacts.firstNames = #"";
}
if (!contacts.lastNames) {
contacts.lastNames = #"";
}
contacts.contactId = ABRecordGetRecordID(person);
//append first name and last name
contacts.fullname = [NSString stringWithFormat:#"%# %#", contacts.firstNames, contacts.lastNames];
// get contacts picture, if pic doesn't exists, show standart one
CFDataRef imgData = ABPersonCopyImageData(person);
NSData *imageData = (__bridge NSData *)imgData;
contacts.image = [UIImage imageWithData:imageData];
if (imgData != NULL) {
CFRelease(imgData);
}
if (!contacts.image) {
contacts.image = [UIImage imageNamed:#"avatar.png"];
}
//get Phone Numbers
NSMutableArray *phoneNumbers = [[NSMutableArray alloc] init];
ABMultiValueRef multiPhones = ABRecordCopyValue(person, kABPersonPhoneProperty);
for(CFIndex i=0; i<ABMultiValueGetCount(multiPhones); i++) {
#autoreleasepool {
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, i);
NSString *phoneNumber = CFBridgingRelease(phoneNumberRef);
phoneNumber = [[phoneNumber componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString:#""];
if (phoneNumber != nil)[phoneNumbers addObject:phoneNumber];
//NSLog(#"All numbers %#", phoneNumbers);
}
}
if (multiPhones != NULL) {
CFRelease(multiPhones);
}
[contacts setNumbers:phoneNumbers];
//get Contact email
NSMutableArray *contactEmails = [NSMutableArray new];
ABMultiValueRef multiEmails = ABRecordCopyValue(person, kABPersonEmailProperty);
for (CFIndex i=0; i<ABMultiValueGetCount(multiEmails); i++) {
#autoreleasepool {
CFStringRef contactEmailRef = ABMultiValueCopyValueAtIndex(multiEmails, i);
NSString *contactEmail = CFBridgingRelease(contactEmailRef);
if (contactEmail != nil)[contactEmails addObject:contactEmail];
// NSLog(#"All emails are:%#", contactEmails);
}
}
if (multiPhones != NULL) {
CFRelease(multiEmails);
}
[contacts setEmails:contactEmails];
[items addObject:contacts];
#ifdef DEBUG
NSLog(#"Person is: %#", contacts.firstNames);
NSLog(#"Phones are: %#", contacts.numbers);
NSLog(#"Email is:%#", contacts.emails);
#endif
}
// } //autoreleasepool
CFRelease(allPeople);
CFRelease(addressBookRef);
CFRelease(source);
return items;
}
now i am getting the contacts and now i am fetching the contacts from
- (NSFetchedResultsController *)fetchedResultsController
{
if (fetchedResultsController == nil)
{
NSManagedObjectContext *moc = [[self appDelegate] managedObjectContext_roster];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"XMPPUserCoreDataStorageObject"
inManagedObjectContext:moc];
NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:#"sectionNum" ascending:YES];
NSSortDescriptor *sd2 = [[NSSortDescriptor alloc] initWithKey:#"displayName" ascending:YES];
NSArray *sortDescriptors = #[sd1, sd2];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
[fetchRequest setSortDescriptors:sortDescriptors];
[fetchRequest setFetchBatchSize:20];
fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:moc
sectionNameKeyPath:#"sectionNum"
cacheName:nil];
[fetchedResultsController setDelegate:self];
NSError *error = nil;
if (![fetchedResultsController performFetch:&error])
{
DDLogError(#"Error performing fetch: %#", error);
NSLog(#"Error performing fetch");
}
}
return fetchedResultsController;
}
now assigning this fetched controller to array like
self.UserArray=[[[self fetchedResultsController] fetchedObjects] mutableCopy];
but unable to fetch the contacts to tableview where i miss please help me out
I am using this code to export contact from ios phonebook to .vcf file. I have used this code for the task. But vcardString is always returning nil. Please help me to solve this issue.
NSMutableArray *contacts=[NSMutableArray alloc] init];
CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!granted) {
dispatch_async(dispatch_get_main_queue(), ^{
});
return;
}
NSMutableArray *contacts = [NSMutableArray array];
NSError *fetchError;
CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:#[CNContactIdentifierKey, [CNContactFormatter descriptorForRequiredKeysForStyle:CNContactFormatterStyleFullName]]];
BOOL success = [store enumerateContactsWithFetchRequest:request error:&fetchError usingBlock:^(CNContact *contact, BOOL *stop) {
[contacts addObject:contact];
}];
if (!success) {
NSLog(#"error = %#", fetchError);
}
// you can now do something with the list of contacts, for example, to show the names
CNContactFormatter *formatter = [[CNContactFormatter alloc] init];
for (CNContact *contact in contacts) {
[contactsArray addObject:contact];
// NSString *string = [formatter stringFromContact:contact];
//NSLog(#"contact = %#", string);
}
//NSError *error;
NSData *vcardString =[CNContactVCardSerialization dataWithContacts:contactsArray error:&error];
NSLog(#"vcardString = %#",vcardString);
}];
Change this line:
CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:#[[CNContactVCardSerialization descriptorForRequiredKeys]]
This fetches all required info for creating a vCard.
I am building a project where I am using ELCImagepickerController for multiple selection and then I am saving those selected image into core data. Now I am fetching those images in another VC and showing them into an UICollectionView.
But the problem I am facing here is the images are not properly showing in collectionView. I am having two confusions.
The images are properly saving into core data or not.
If the images are saved, then properly fetching or not.
Here I am entering selected images into core data
- (void)imagePicker:(SNImagePickerNC *)imagePicker didFinishPickingWithMediaInfo:(NSMutableArray *)info
{
_arrImages = [[NSMutableArray alloc]init];
_imgdata = [[NSMutableData alloc]init];
AppDelegate* app=(AppDelegate*)[[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = app.managedObjectContext;
Albums *objPhotos = (Albums *)[NSEntityDescription insertNewObjectForEntityForName:#"Albums" inManagedObjectContext:context];
//get images
for (int i = 0; i < info.count; i++) {
ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
[assetLibrary assetForURL:info[i] resultBlock:^(ALAsset *asset) {
UIImage *image = [UIImage imageWithCGImage:[asset aspectRatioThumbnail]];
_imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
[objPhotos setPhotosInAlbum:self.imageData];
} failureBlock:^(NSError *error) { }];
}
NSError * err = nil;
[context save:&err];
if (![context save:&err]) {
NSLog(#"Can't Save! %# %#", err, [err localizedDescription]);
}
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Success!!" message:#"Photos Successfully Selected!" delegate:self cancelButtonTitle:#"DONE" otherButtonTitles:nil];
[alert show];
}
Here I am fetching those selected images
-(NSArray *)getMenCategoryList
{
AppDelegate* app=(AppDelegate*)[[UIApplication sharedApplication]delegate];
NSManagedObjectContext *moc=app.managedObjectContext;
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Albums" inManagedObjectContext:moc];
[fetch setEntity:entity];
NSError *error;
NSArray *result = [moc executeFetchRequest:fetch error:&error];
if (!result) {
return nil;
}
return result;
}
I am calling the fetching function in - (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section and returning the array count
- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [[self getMenCategoryList] count];
}
And lastly, populating the images into collectionView here
- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = (UICollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:#"albumCollectionViewCellCell" forIndexPath:indexPath];
Photos *objAlbumPhotos = (Photos *)[[self getMenCategoryList] objectAtIndex:indexPath.row];
UIImage *albumImg = [UIImage imageWithData:[objAlbumPhotos valueForKey:#"photosInAlbum"]];
UIImageView *photosimageview = (UIImageView *)[cell.contentView viewWithTag:1];
photosimageview.image = albumImg;
return cell;
}
Any help is highly appreciated.
NOTE: i am just edit your code Please confirm first as per your code and edit as per your requirement
step 1: generate Unique file name and save your image with that file name to your file path.
step 2: after successfully write your file then save that path to your core data.
step 3: for fetching use core data path to get images from directory.
- (NSString*)generateFileNameWithExtension:(NSString *)extensionString {
// Extenstion string is like #".png"
NSDate *time = [NSDate date];
NSDateFormatter* df = [NSDateFormatter new];
[df setDateFormat:#"dd-MM-yyyy-hh-mm-ss"];
NSString *timeString = [df stringFromDate:time];
int r = arc4random() % 100;
int d = arc4random() % 100;
NSString *fileName = [NSString stringWithFormat:#"File-%#%d%d%#", timeString, r , d , extensionString ];
NSLog(#"FILE NAME %#", fileName);
return fileName;
}
- (void)imagePicker:(SNImagePickerNC *)imagePicker didFinishPickingWithMediaInfo:(NSMutableArray *)info
{
_arrImages = [[NSMutableArray alloc]init];
_imgdata = [[NSMutableData alloc]init];
AppDelegate* app=(AppDelegate*)[[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = app.managedObjectContext;
Albums *objPhotos = (Albums *)[NSEntityDescription insertNewObjectForEntityForName:#"Albums" inManagedObjectContext:context];
//get images
for (int i = 0; i < info.count; i++) {
ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
[assetLibrary assetForURL:info[i] resultBlock:^(ALAsset *asset) {
UIImage *image = [UIImage imageWithCGImage:[asset aspectRatioThumbnail]];
_imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
NSString *strfilename = [self generateFileNameWithExtension:#".jpg"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:strfilename];
[_imageData writeToFile:filePath atomically:YES];
[objPhotos setPhotosInAlbum:filePath];
} failureBlock:^(NSError *error) { }];
}
NSError * err = nil;
[context save:&err];
if (![context save:&err]) {
NSLog(#"Can't Save! %# %#", err, [err localizedDescription]);
}
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Success!!" message:#"Photos Successfully Selected!" delegate:self cancelButtonTitle:#"DONE" otherButtonTitles:nil];
[alert show];
}
I create one application and I read many data in table View from JSON and I want parsed this JSON and store in sqlite but I dont know from where should I start?
this is parsed my json code :
#implementation TableViewController
{
NSArray *news;
NSMutableData *data;
NSString *title;
NSMutableArray *all;
}
#synthesize mainTable;
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"News";
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *url = [NSURL URLWithString:#"http://zacandcatie.com/YouTube/json.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[con start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
data = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
[data appendData:theData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
news = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
for (int i =0; i < [news count]; i++)
{
NSIndexPath *indexPath = [self.mainTable indexPathForSelectedRow];
title =[[news objectAtIndex:indexPath.row+i]objectForKey:#"title"];
if (!all) {
all = [NSMutableArray array];
}
[all addObject:title];
}
NSLog(#"%#",all);
[mainTable reloadData];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *errorView = [[UIAlertView alloc]initWithTitle:#"Error" message:#"The Connection has been LOST" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[errorView show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
you my json url. I want store "title"&"date_string" value in sqlite.
please guide me!!!
After parsing you data in the form of NSDictionary you can create a query of insert into and fire the query n your data will be save into your database
-(void)InsertRecords:(NSMutableDictionary *)dict
{
sqlite3_stmt *stmt;
sqlite3 *cruddb;
NSMutableString *str = [NSMutableString stringWithFormat:#"Insert into tblName ("];
for (int i = 0; i<[[dict allKeys] count]; i++)
{
[str appendFormat:#"%#,",[[dict allKeys] objectAtIndex:i]];
}
[str appendFormat:#")values ("];
for (int i = 0; i<[[dict allKeys] count]; i++)
{
[str appendFormat:#"%#,",[dict valueForKey:[[dict allKeys] objectAtIndex:i]]];
}
[str appendFormat:#");"];
NSLog(#"qry : %#",str);
const char *sql = [str UTF8String]; ;
if((sqlite3_open([database UTF8String], &cruddb)==SQLITE_OK))
{
if (sqlite3_prepare(database, sql, -1, &stmt, NULL) ==SQLITE_OK)
{
sqlite3_step(stmt);
sqlite3_finalize(stmt);
}
else
{
NSLog(#"Problem with prepare statement: %s", sqlite3_errmsg(database));
}
sqlite3_close(database);
}
else
{
NSLog(#"An error has occured: %s",sqlite3_errmsg(database));
}
}
Try this.
Continuing #Divz Ans...
you will have create the .sqlite file. And there is nothing easier than this.
There are two ways(that i know) to create sqlite file,
1> you can download SQLite Manager add-on in firefox, where you can manipulate data in database graphically.
Or,
2> you can use Terminal with a single line command, sqlite3 dbFileName.sqlite. enter,
where you will get sqlite> now start with further SQL(create/insert/update..) queries.
you can find your sqlite file at MacHD>users>admin(not shared one)>yourFile.sqlite or, finder---go>home>yourFile.sqlite
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
db=[[SKDatabase alloc]initWithFile:#"student.sqlite"];
NSURL *url=[NSURL URLWithString:#"..........Your Url............"];
NSURLRequest *json_request=[[NSURLRequest alloc]initWithURL:url];
NSData *data=[NSURLConnection sendSynchronousRequest:json_request returningResponse:nil error:nil];
NSMutableDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSMutableArray *student_ary=[dic objectForKey:#"students"];
for (NSMutableArray *student_info in student_ary) {
NSMutableDictionary *insert=[[NSMutableDictionary alloc]initWithCapacity:2];
NSMutableDictionary *info=[student_info mutableCopy];
[insert setObject:[info objectForKey:#"name"] forKey:#"name"];
[insert setObject:[info objectForKey:#"city"] forKey:#"city"];
[db insertDictionary:insert forTable:#"student_info"];
}
})
//.m file view....
-(void)viewDidAppear:(BOOL)animated
{
NSString *qry=#"select * from student_info";
ary=[[db lookupAllForSQL:qry] mutableCopy];
[tableView reloadData];
}
You can do some thing like this :
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// tableview cell setup
NSArray* keys = [self.data allKeys];
cell.textLabel.text = [self.data objectForKey:[keys objectAtIndex:indexPath.row]];
return cell;
}
Please refer this links to have data in order in dictionary
NSDictionary with ordered keys
The following code :
-(NSArray *)getContentsWithContextTypes:(NSArray *)contextTypes
contextData:(NSArray *)contextData
{
__block NSString *query = #"SELECT * FROM Texts_original1 WHERE ";
[contextData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSString *attributeName = [self.contextTypeToDBQueryTexts
objectForKey:contextTypes[idx]];
query = [query stringByAppendingFormat:#"%# = \"%#\"", attributeName, obj];
if(idx != contextData.count - 1)
{
query = [query stringByAppendingString:#" AND "];
}
}];
[self.db open];
FMResultSet *results = [self.db executeQuery:query];
NSMutableArray *array = [NSMutableArray array];
while([results next])
{
Content *content = [[TextualContent alloc] initWithResults:results];
[array addObject:content];
}
[self.db close];
return array;
}
Generates the following error when I run it :
Error calling sqlite3_step (21: out of memory) rs
It happens half way through the loop. There should be 33 results. After 17 I get that error and the loop exits. Any Ideas? Thanks.
It's important to know that you close the FMResultSet object, as it will cause memory problems.
Do it as follows, [resultSet close]
I am not getting into your code logic but, I will make some modifications in database code.
Try the following:
-(NSArray *)getContentsWithContextTypes:(NSArray *)contextTypes
contextData:(NSArray *)contextData
{
__block NSString *query = #"SELECT * FROM Texts_original1 WHERE ";
[contextData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
NSString *attributeName = [self.contextTypeToDBQueryTexts
objectForKey:contextTypes[idx]];
query = [query stringByAppendingFormat:#"%# = \"%#\"", attributeName, obj];
if(idx != contextData.count - 1)
{
query = [query stringByAppendingString:#" AND "];
}
}];
self.db = [FMDatabase databaseWithPath:[self getDBPath]];
if(![db open])
{
NSLog(#"Could not open DB");
return nil;
}
FMResultSet *results = [self.db executeQuery:query];
NSMutableArray *array = [NSMutableArray array];
while([results next])
{
Content *content = [[TextualContent alloc] initWithResults:results];
[array addObject:content];
}
[results close]; //VERY IMPORTANT!
[self.db close];
return array;
}