Repeating UIAlert code over and over - objective-c

I have this code:
-(IBAction)action2:(id)sender{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Confirm" message:#"If you press of a new group with the name you have set will be created" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles: #"Ok", nil];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"Ok"])
{
NSString *destDir = [NSString stringWithFormat:#"/sandbox/%#/", namegroup.text];
NSString *filename5 = namegroup.text;
NSString *filename6 = #"group";
NSString *filename7 = #"groupdata";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath5 = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat:#"%#", filename7]];
NSMutableArray *titles = [NSMutableArray array];
[titles addObject:filename5];
NSMutableArray *keys = [NSMutableArray array];
[keys addObject:filename6];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:titles forKeys:keys];
NSString *jsonString = [dict JSONRepresentation];
NSData *jsonData = [jsonString dataUsingEncoding: NSUTF8StringEncoding];
[jsonData writeToFile: getImagePath5 atomically: YES];
[[self restClient] uploadFile:filename7 toPath:destDir
withParentRev:nil fromPath:getImagePath5];
}
}
If I press Ok button, the code is repeated over and over. how can I repeat it only 1 time??

I found out that there was another alert with the same cancel title, and when this was pressed it re-launched the same code. Thanks however for the help.

Related

how to zip and email a file using objective c?

I need to zip my log file and email it. I'm using Objective-zip for zipping my file. And this is my code
-(void)mailLogFile {
if ([MFMailComposeViewController canSendMail]) {
NSDictionary *user = [[DBHelper getSharedInstance] getCurrentUser];
NSString *propertyQuery = [NSString stringWithFormat:#"SELECT RecentActivityId,PropertyPIC,PropertyId,Message,IsSynced,ActivityTime,ErrorCode,ErrorMessage,ErrorData,EntityId,TableNames From RecentActivity ORDER BY ActivityTime desc"];
NSArray *resultArry = [[DBHelper getSharedInstance] getRecordsBySQL:propertyQuery];
NSLog(#"This is the eNVDS in Recent Activity:%#" ,resultArry);
[[DBHelper getSharedInstance] AddLogFile:[NSString stringWithFormat:#"This is the eNVDS in Recent Activity:%#" ,resultArry]];
NSPredicate *notsynced = [NSPredicate predicateWithFormat:#"IsSynced == 0 || IsSynced == %#",#"0"];
NSArray *notsyncedenvds = [resultArry filteredArrayUsingPredicate:notsynced];
NSLog(#"This is the eNVDS in Recent Activity which is not synced:%#" ,notsyncedenvds);
[[DBHelper getSharedInstance] AddLogFile:[NSString stringWithFormat:#"This is the eNVDS in Recent Activity which is not synced:%#" ,notsyncedenvds]];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *WritableDBPath= [documentsDirectory stringByAppendingPathComponent:#"Logfile.txt"];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"test.zip"];
NSData *zipdata = [NSData dataWithContentsOfFile:path];
NSData *data = [NSData dataWithContentsOfFile:WritableDBPath];
//OZZipFile *readFile = [[OZZipFile alloc] initWithFileName:path mode:OZZipFileModeCreate];
OZZipFile *zipFile32= [[OZZipFile alloc] initWithFileName:path mode:OZZipFileModeCreate];
OZZipWriteStream *stream= [zipFile32 writeFileInZipWithName:#"Logfile.txt" compressionLevel:OZZipCompressionLevelBest];
[stream writeData:data];
[stream finishedWriting];
NSString *emailTitle = [NSString stringWithFormat:#"Log file of %#",[NSDate date]];
NSMutableString *messageBody = [NSMutableString stringWithFormat:#"Login with %#",user[#"Username"]];
if(![user[#"PropertyName"] isKindOfClass:[NSNull class]])[messageBody appendFormat:#"\n%#",user[#"PropertyName"]];
[messageBody appendFormat:#"\nApp version : %#",APP_VERSION];
[messageBody appendFormat:#"\nPlease describe your problem scenario here."];
[messageBody appendFormat:#"\n\n\nThanks"];
NSArray *toRecipents = [NSArray arrayWithObject:#"support#aglive.com"];
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setMessageBody:messageBody isHTML:NO];
[mc setToRecipients:toRecipents];
[mc addAttachmentData:zipdata mimeType:#"application/zip" fileName:#"test.zip"];
[self presentViewController:mc animated:YES completion:nil];
[zipFile32 close];
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Aglive Pro" message:#"You have not configured your mail account. Please configure your mail account from the device settings." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
}
right now I'm able to send a zip file in email but when I do unzip and open the file in my mobile or mac I get alert saying that The document “Logfile 4.txt” could not be opened. The file isn’t in the correct format. I don't know where I'm going wrong.
This code worked for me
-(void)mailLogFile {
if ([MFMailComposeViewController canSendMail]) {
NSDictionary *user = [[DBHelper getSharedInstance] getCurrentUser];
NSString *propertyQuery = [NSString stringWithFormat:#"SELECT RecentActivityId,PropertyPIC,PropertyId,Message,IsSynced,ActivityTime,ErrorCode,ErrorMessage,ErrorData,EntityId,TableNames From RecentActivity ORDER BY ActivityTime desc"];
NSArray *resultArry = [[DBHelper getSharedInstance] getRecordsBySQL:propertyQuery];
NSLog(#"This is the eNVDS in Recent Activity:%#" ,resultArry);
[[DBHelper getSharedInstance] AddLogFile:[NSString stringWithFormat:#"This is the eNVDS in Recent Activity:%#" ,resultArry]];
NSPredicate *notsynced = [NSPredicate predicateWithFormat:#"IsSynced == 0 || IsSynced == %#",#"0"];
NSArray *notsyncedenvds = [resultArry filteredArrayUsingPredicate:notsynced];
NSLog(#"This is the eNVDS in Recent Activity which is not synced:%#" ,notsyncedenvds);
[[DBHelper getSharedInstance] AddLogFile:[NSString stringWithFormat:#"This is the eNVDS in Recent Activity which is not synced:%#" ,notsyncedenvds]];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *WritableDBPath= [documentsDirectory stringByAppendingPathComponent:#"Logfile.txt"];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"Logfile.zip"];
NSData *zipdata = [NSData dataWithContentsOfFile:path];
NSData *data = [NSData dataWithContentsOfFile:WritableDBPath];
OZZipFile *zipFile32= [[OZZipFile alloc] initWithFileName:path mode:OZZipFileModeCreate];
//NSData *zipdata2 = [NSData dataWithContentsOfFile:zipFile32];
OZZipWriteStream *stream= [zipFile32 writeFileInZipWithName:#"LogFile.txt" compressionLevel:OZZipCompressionLevelBest];
[stream writeData:data];
[stream finishedWriting];
[zipFile32 close];
NSString *emailTitle = [NSString stringWithFormat:#"Log file of %#",[NSDate date]];
NSMutableString *messageBody = [NSMutableString stringWithFormat:#"Login with %#",user[#"Username"]];
if(![user[#"PropertyName"] isKindOfClass:[NSNull class]])[messageBody appendFormat:#"\n%#",user[#"PropertyName"]];
[messageBody appendFormat:#"\nApp version : %#",APP_VERSION];
[messageBody appendFormat:#"\nPlease describe your problem scenario here."];
[messageBody appendFormat:#"\n\n\nThanks"];
NSArray *toRecipents = [NSArray arrayWithObject:#"support#aglive.com"];
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setMessageBody:messageBody isHTML:NO];
[mc setToRecipients:toRecipents];
//
if(zipdata== 0 && zipdata==nil)
{
[self mailLogFile];
}
else
{
[mc addAttachmentData:zipdata mimeType:#"application/zip" fileName:#"Logfile.zip"];
[self presentViewController:mc animated:YES completion:nil];
}

How to attach image in vCard (vcf file) using Objective C?

In my project I need to create and send a vCard (vcf file) that must include an image too. I did everything right except I can not add image to the vCard. I have shared my code below.
- (IBAction)shareButtonPressed:(UIButton *)sender {
NSError *error;
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:#"vCard.vcf"];
[[self vCardRepresentation] writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:#[#"Test", [NSURL fileURLWithPath:filePath]] applicationActivities:nil];
activityVC.excludedActivityTypes = #[UIActivityTypePostToWeibo, UIActivityTypeAssignToContact, UIActivityTypeMessage, UIActivityTypeCopyToPasteboard];
[self presentViewController:activityVC animated:YES completion:^{
}];
}
- (NSString *)vCardRepresentation
{
NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:#"Rokon"], 1.0);
[mutableArray addObject:#"BEGIN:VCARD"];
[mutableArray addObject:#"VERSION:3.0"];
[mutableArray addObject:[NSString stringWithFormat:#"FN:%#", #"Rokon"]];
[mutableArray addObject:[NSString stringWithFormat:#"TEL:%#",#"+8801811536248"]];
[mutableArray addObject:[NSString stringWithFormat:#"PHOTO;BASE64:%#",[imageData base64EncodedDataWithOptions:0]]];
[mutableArray addObject:#"END:VCARD"];
return [mutableArray componentsJoinedByString:#"\n"];
}
- (void)shareContact{
[self emptySandbox];
NSString *contactName = [NSString stringWithFormat:#"%# %#",[Person sharedInstance].firstName, [Person sharedInstance].lastName];
NSError *error;
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.vcf", contactName]];
[[self vCardRepresentation] writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:#[contactName, [NSURL fileURLWithPath:filePath]] applicationActivities:nil];
activityVC.excludedActivityTypes = #[UIActivityTypePostToWeibo, UIActivityTypeAssignToContact, UIActivityTypeCopyToPasteboard];
[activityVC setValue:contactName forKey:#"subject"];
[self presentViewController:activityVC animated:YES completion:^{
}];
}
- (NSString *)vCardRepresentation
{
NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
NSData *imageData = UIImageJPEGRepresentation([Person sharedInstance].profileImage, 1.0);
[mutableArray addObject:#"BEGIN:VCARD"];
[mutableArray addObject:#"VERSION:3.0"];
[mutableArray addObject:[NSString stringWithFormat:#"FN:%#", [NSString stringWithFormat:#"%#%#", [Person sharedInstance].firstName, [Person sharedInstance].lastName]]];
[mutableArray addObject:[NSString stringWithFormat:#"TEL:%#",[Person sharedInstance].phone]];
[mutableArray addObject:[NSString stringWithFormat:#"email:%#", [Person sharedInstance].email]];
[mutableArray addObject:[NSString stringWithFormat:#"PHOTO;BASE64;ENCODING=b;TYPE=JPEG:%#",[imageData base64EncodedStringWithOptions:0]]];
[mutableArray addObject:#"END:VCARD"];
return [mutableArray componentsJoinedByString:#"\n"];
}
-(void)emptySandbox
{
NSFileManager *fileMgr = [[NSFileManager alloc] init];
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *files = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:nil];
while (files.count > 0) {
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *directoryContents = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error];
if (error == nil) {
for (NSString *path in directoryContents) {
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:path];
BOOL removeSuccess = [fileMgr removeItemAtPath:fullPath error:&error];
files = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:nil];
if (!removeSuccess) {
// Error
}
}
} else {
// Error
}
}
}

How to handle the UIActivityViewController "Cancel" button

There is a "cancel" button that comes by default with UIActivityViewController. How can I call a method when that button is pressed?
I have written this code to share the audio file.
NSURL* outURL;
UIActivityViewController *controller;
if (&UIActivityTypeAirDrop != NULL) {
controller.excludedActivityTypes = #[UIActivityTypeAirDrop];
for (int i=0;i<[arrayselecturls count];i++) {
str_SongsselectName=[[arrayselecturls objectAtIndex:i] objectForKey:#"Song"];
NSString* ext = [TSLibraryImport extensionForAssetURL:[[arrayselecturls objectAtIndex:i] objectForKey:#"SongURl"]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
outURL = [[NSURL fileURLWithPath:[documentsDirectory stringByAppendingPathComponent:[[arrayselecturls objectAtIndex:i] objectForKey:#"Song"]]] URLByAppendingPathExtension:ext];
NSString *str_selectfilename=[NSString stringWithFormat:#"%#.mp3",str_SongsselectName];
// NSURL *url = outURL;
// NSLog(#"url is %#",url);
NSArray *objectsToShare = [NSArray arrayWithObjects:outURL,str_selectfilename, nil];
// objectsToShare = #[outURL];
controller = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
// Exclude all activities except AirDrop.
NSArray *excludedActivities = #[UIActivityTypePostToTwitter, UIActivityTypePostToFacebook,
UIActivityTypePostToWeibo,
UIActivityTypeMessage, UIActivityTypeMail,
UIActivityTypePrint, UIActivityTypeCopyToPasteboard,
UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll,
UIActivityTypeAddToReadingList, UIActivityTypePostToFlickr,
UIActivityTypePostToVimeo, UIActivityTypePostToTencentWeibo];
controller.excludedActivityTypes = excludedActivities;
}
[self presentViewController:controller animated:YES completion:nil];
}
else{
UIAlertView *Alert = [[UIAlertView alloc] initWithTitle:#"Sorry" message:#"Your device has no Airdrop!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[Alert show];
}
oooooop!
I got the solution.This solution is working fine for me.
-(IBAction)ActionArtsist_airdropClick:(id)sender{
view_shareView.hidden=YES;
borderImageView . hidden =YES;
darkBg . hidden =YES;
view_artistdarlView.hidden=YES;
tblv_albumSongTableView.userInteractionEnabled=YES;
Data = [NSData dataWithContentsOfURL: exportURL];
UIActivityViewController *controller;
if (&UIActivityTypeAirDrop != NULL) {
controller.excludedActivityTypes = #[UIActivityTypeAirDrop];
NSString *str_selectfilename;
for (int i=0;i<[arr_atistsongsSelct count];i++) {
str_songsSlelectName=[[arr_atistsongsSelct objectAtIndex:i] objectForKey:#"songsName"];
NSString* ext = [TSLibraryImport extensionForAssetURL:[[arr_atistsongsSelct objectAtIndex:i] objectForKey:#"songsURl"]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSURL* outURL = [[NSURL fileURLWithPath:[documentsDirectory stringByAppendingPathComponent:[[arr_atistsongsSelct objectAtIndex:i] objectForKey:#"songsName"]]] URLByAppendingPathExtension:ext];
str_selectfilename=[NSString stringWithFormat:#"%#.mp3",str_songsSlelectName];
NSArray *objectsToShare = [NSArray arrayWithObjects:outURL,str_selectfilename, nil];
controller = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
// Exclude all activities except AirDrop.
NSArray *excludedActivities = #[UIActivityTypePostToTwitter, UIActivityTypePostToFacebook,
UIActivityTypePostToWeibo,
UIActivityTypeMessage, UIActivityTypeMail,
UIActivityTypePrint, UIActivityTypeCopyToPasteboard,
UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll,
UIActivityTypeAddToReadingList, UIActivityTypePostToFlickr,
UIActivityTypePostToVimeo, UIActivityTypePostToTencentWeibo];
controller.excludedActivityTypes = excludedActivities;
}
This is the handling function.
**[controller setCompletionHandler:^(NSString *activityType, BOOL completed) {
if (!completed)
{
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
[self performSelector:#selector(ActiviHideArtistSong) withObject:self afterDelay:4.0 ];
}
return;
}];**
upto here
[self presentViewController:controller animated:YES completion:nil];
}
else{
UIAlertView *warningAlert = [[UIAlertView alloc] initWithTitle:#"Sorry" message:#"Your device has no Airdrop!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[warningAlert show];
}
}
-(void)ActiviHideArtistSong{
[self btnimageArtistSongscheck_lick:nil];
}

Writing to .plist returns "Success!" but ends up blank

Here is my code:
-(IBAction)btnSaveInfo:(UIButton *)sender {
NSMutableArray *data = [[NSMutableArray alloc] init];
NSDictionary *appInfo = [NSDictionary dictionaryWithObjectsAndKeys: fieldAPI.text, #"App API", fieldID.text, #"App ID", fieldName.text, #"App Name", nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *newPath = [documentsDirectory stringByAppendingPathComponent:#"AppData.plist"];
NSMutableArray *appdata = [NSMutableArray arrayWithContentsOfFile:newPath];
[appdata addObject:appInfo];
NSLog(#"%#",appdata);
[appdata writeToFile:newPath atomically:YES];
if ([data writeToFile:newPath atomically:YES]) {
NSLog(#"Success!");
NSMutableArray *finalData = [NSMutableArray arrayWithContentsOfFile:newPath];
NSLog(#"Final array:\n\n%#",finalData);
[self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}
else {
NSLog(#"Error...");
}
[data release];
}
My NSLogs return
2012-12-23 01:20:37.628 Parse Push[38052:c07] (
{
"App API" = asdf;
"App ID" = adsf;
"App Name" = asdf;
}
)
2012-12-23 01:20:37.932 Parse Push[38052:c07] Success!
2012-12-23 01:20:37.933 Parse Push[38052:c07] Final array:
(
)
Is there an error with my code, or something that I'm missing? I am new to interacting with .plists, so I would appreciate any help, thanks!
The problem is here
if ([data writeToFile:newPath atomically:YES]) {
You are writing again an empty array here
Use this
[appdata addObject:appInfo];
NSLog(#"%#",appdata);
if ([appdata writeToFile:newPath atomically:YES]){

JSON representation of NSDictionary

In my app a user can create UITextFields. to each field a tag is added, so that the tags correspond to the cases: 1, 2, 3, 4, ... then I add everything in a NSDictionary, and a json representation:
-(IBAction)buttonDropBoxuploadPressed:(id)sender{
//screenshot
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy_MM_dd"];
NSString *filename = [NSString stringWithFormat:#"By: %# ",
[formatter stringFromDate:[NSDate date]]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat:#"%#", filename] ];
//[data writeToFile:path atomically:YES];
//NSString *destDir = #"/sandbox/";
// [[self restClient] uploadFile:filename toPath:destDir
// withParentRev:nil fromPath:path];
// [[self restClient] loadMetadata:#"/sandbox/"];
//JSON
NSString *object;
NSString *object2;
NSString *object3;
NSString *object4;
NSString *object5;
NSString *object6;
NSString *object7;
NSString *object8;
NSString *object9;
NSString *object10;
NSString *object11;
NSString *object12;
NSString *object13;
NSString *object14;
NSString *object15;
for (UITextField *text in messagename) {
int touchedtag = text.tag;
NSUInteger tagCount = touchedtag;
switch (tagCount) {
case 1:
object = [NSString stringWithFormat:#"%#", text.text];
break;
case 2:
object2 = [NSString stringWithFormat:#"%#", text.text];
break;
case 3:
object3 = [NSString stringWithFormat:#"%#", text.text];
break;
case 4:
object4 = [NSString stringWithFormat:#" %#", text.text];
break;
case 5:
object5 = [NSString stringWithFormat:#"%#", text.text];
break;
case 6:
object6 = [NSString stringWithFormat:#"%#", text.text];
break;
case 7:
object7 = [NSString stringWithFormat:#"%#", text.text];
break;
case 8:
object8 = [NSString stringWithFormat:#"%#", text.text];
break;
case 9:
object9 = [NSString stringWithFormat:#"%#", text.text];
break;
case 10:
object10 = [NSString stringWithFormat:#"%#", text.text];
break;
case 11:
object11 = [NSString stringWithFormat:#"%#", text.text];
break;
case 12:
object12 = [NSString stringWithFormat:#"%#", text.text];
break;
case 13:
object13 = [NSString stringWithFormat:#"%#", text.text];
break;
case 14:
object14 = [NSString stringWithFormat:#"%#", text.text];
break;
case 15:
object15 = [NSString stringWithFormat:#"%#", text.text];
break;
default :
break;
}
}
//arrays
NSString * objects[] = { object, object2, object3, object4, object5, object6, object7, object8, object9, object10, object11, object12, object13, object14, object15};
NSMutableArray *textnameobject = [[NSMutableArray alloc] initWithCapacity:b];
textnameobject = [NSMutableArray arrayWithObjects:objects count:b];
NSMutableArray *textnamekeys = [[NSMutableArray alloc] initWithCapacity:b];
NSString * textnumber[] = {#"title", #"title", #"title",#"title", #"title", #"title", #"title", #"title", #"title", #"title", #"title", #"title", #"title", #"title"};
textnamekeys = [NSMutableArray arrayWithObjects:textnumber count:b];
//arrays
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObject: textnameobject forKey:textnamekeys];
/*
NSArray *objects2 = [NSArray arrayWithObjects:jsonDictionary, nil];
NSArray *keys2 = [NSArray arrayWithObjects:allkeys, nil];
NSDictionary *mainDict = [NSDictionary dictionaryWithObjects:objects2 forKeys:keys2];
*/
NSString* jsonString = [jsonDictionary JSONRepresentation];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
[jsonData writeToFile:path atomically:YES];
NSString *destDir = #"/sandbox/";
[[self restClient] uploadFile:filename toPath:destDir
withParentRev:nil fromPath:path];
[[self restClient] loadMetadata:#"/sandbox/"];
//JSON
}
When I press the button I get the following error:
JSONRepresentation failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=1 \"JSON object key must be string\" UserInfo=0x2e8370 {NSLocalizedDescription=JSON object key must be string}"
)
and consequentially a dropbox error. this worked on my previous app and the code is exactly the same. the json library is added correctly. I can't understand!! Please help!
Your code, rewritten.
- (IBAction)buttonDropBoxUploadPressed: (id)sender
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat: #"yyyy_MM_dd"];
NSString *filename = [NSString stringWithFormat: #"By: %# ", [formatter stringFromDate: [NSDate date]]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex: 0];
NSString *path = [documentsDirectory stringByAppendingPathComponent: filename];
NSMutableDictionary *titles = [NSMutableDictionary dictionary];
for (UITextField *textField in messagename)
{
[titles setObject: textField.text forKey: #"title"];
// as you can see, here you're replacing the value # at key "title" with a new object on every pass
}
NSString *jsonString = [titles JSONRepresentation];
NSData *jsonData = [jsonString dataUsingEncoding: NSUTF8StringEncoding];
[jsonData writeToFile: path atomically: YES];
NSString *destDir = #"/sandbox/";
[[self restClient] uploadFile: filename toPath: destDir withParentRev: nil fromPath: path];
[[self restClient] loadMetadata: #"/sandbox/"];
}
However, regarding my comment, you're not actually serializing your text fields' text into anything usable. At the end of this, at best, you'll have something that looks like this:
{
"title": "My Text Field Value"
}
Though I'm also relatively certain that one or more of your text fields' text is nil, which is causing your JSON problem.