XMPP resource id getting change while login more then one device - xmpp

i have logged in two devices with same user id and password, so when destination device send voice or image to client .The one device getting the destination message but another one device not getting the destination message . because the resource id is getting change when login in two devices. Its showing error message 503()
(NSString *)full
{
if (user)
{
if (resource)
{
//----- here i am getting the resource ID -------
[[NSUserDefaults standardUserDefaults]setObject:resource forKey:#"GETRESOURCE"];
[[NSUserDefaults standardUserDefaults]synchronize];
return [NSString stringWithFormat:#"%##%#/%#", user, domain, resource];
}
else
{
return [NSString stringWithFormat:#"%##%#", user, domain];
}
} else {
if (resource)
return [NSString stringWithFormat:#"%#/%#", domain, resource];
else
return domain;
}
}
(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
CGFloat maxCompression = 0.1f;
NSData *imageData = UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage], maxCompression);
[messageType addObject:#"1"];
//---- now implementing the resource id here i getting 503 Error----
NSString *resourceStr = [[NSUserDefaults standardUserDefaults] valueForKey:#"GETRESOURCE"];
XMPPJID *jid = [XMPPJID jidWithString:[NSString stringWithFormat:#"%#/%#", receiver, resourceStr]];
[fileTransfer initiateFileTransferTo:jid withData:imageData];
self.willSendImage = [UIImage imageWithData:imageData];
[messageArray addObject:[NSDictionary dictionaryWithObject:self.willSendImage forKey:#"image"]];
[self.timestamps addObject:[NSDate date]];
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"YYYY-MM-dd HH:mm:ss Z"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
[dbHandler insertChatHistory:#"image" imageData:imageData receiveType:2 mediaType:2 receiverName:titleName date:dateString];
[self finishSend];
[JSMessageSoundEffect playMessageSentSound];
[self scrollToBottomAnimated:YES];
[self reloadMessages];
[self dismissViewControllerAnimated:YES completion:NULL];
}

//--- I WILL SEND THE IMAGE AS A STRING FORMET ITS WORKED FOR ME
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
CGFloat maxCompression = 0.1f;
UIImage * getimage =[self imageWithImage:[info objectForKey:UIImagePickerControllerOriginalImage]];
NSData *imageData = UIImageJPEGRepresentation(getimage, maxCompression);
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"YYYY-MM-dd HH:mm:ss Z"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
//--- convert image to string -----
NSString* imageString = [imageData base64EncodedStringWithOptions:0];
//---- new change --
imageString = [imageString stringByAppendingString:#".IMAGE"];
//-------------
if ([imageString length] > 0)
{
[dbHandler insertChatHistory:imageString imageData:nil receiveType:2 mediaType:1 receiverName:titleName date:dateString];
NSXMLElement *body = [NSXMLElement elementWithName:#"body"];
[body setStringValue:imageString];
NSXMLElement *message = [NSXMLElement elementWithName:#"message"];
[message addAttributeWithName:#"type" stringValue:#"chat"];
[message addAttributeWithName:#"to" stringValue:receiver]; //--- jenish ---
[message addChild:body];
[self.xmppStream sendElement:message];
[messageType addObject:#"1"];
[messageArray addObject:[NSDictionary dictionaryWithObject:imageString forKey:#"Text"]];
[self.timestamps addObject:[NSDate date]];
}
[self finishSend];
[JSMessageSoundEffect playMessageSentSound];
[self scrollToBottomAnimated:YES];
[self reloadMessages];
[self dismissViewControllerAnimated:YES completion:NULL];
}

Related

Information not being received from server?

Okay, my problem is very simple. Below is my code that is receiving prices from an API, in my code I want the today current price to be displayed, yesterdays price, and the change in percent from yesterday to today. Unfortunately, only the current price is showing properly, but the yesterday and the percent change just show N/A.
Any help is appreciated!
if (refreshing) return;
refreshing = YES;
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = YES;
//self.priceLabel.text = #"Loading...";
//self.yesterdayLabel.text = #"Loading...";
//self.changeLabel.text = #"Loading...";
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"https://coinbase.com/api/v1/prices/spot_rate"]] queue:[NSOperationQueue mainQueue] completionHandler:^ (NSURLResponse *req, NSData *recv, NSError *err) {
if (err) {
// report
[self setCurrentPrice:#"N/A"];
refreshing = NO;
return;
}
NSError *newError = nil;
NSDictionary *serial = [NSJSONSerialization JSONObjectWithData:recv options:0 error:&newError];
if (newError) {
// report
[self setCurrentPrice:#"N/A"];
refreshing = NO;
return;
}
NSString *amount = [serial objectForKey:#"amount"];
NSString *price = [NSString stringWithFormat:#"%# %#", amount, [serial objectForKey:#"currency"]];
[self setCurrentPrice:[NSString stringWithFormat:#"%#", price]];
// maybe setup a better method.
float diff = [yesterdaysPrice floatValue];
if (diff == 0.0)
self.differenceInPrices = #"N/A";
else {
float amt = [amount floatValue];
float percentChange = amt/diff;
if ((diff == 0) || (amt == diff))
percentChange = 0.00;
percentChange *= 100.00;
self.differenceInPrices = [NSString stringWithFormat:#"%f%%", percentChange];
}
NSMutableDictionary *saveState = [[[NSUserDefaults standardUserDefaults] objectForKey:#"save"] mutableCopy];
[saveState setObject:price forKey:#"price"];
[saveState setObject:yesterdaysPrice forKey:#"lastCheckedPrice"];
NSDateComponents *compon = [[NSCalendar currentCalendar] components:(NSUndefinedDateComponent) fromDate:[NSDate date]];
[saveState setObject:[NSString stringWithFormat:#"%ld", (usingYesterdaysPrices ? [[saveState objectForKey:#"day"] intValue] : [compon day])] forKey:#"day"];
[[NSUserDefaults standardUserDefaults] setObject:saveState forKey:#"save"];
[[NSUserDefaults standardUserDefaults] synchronize];
self.priceLabel.text =self.currentPrice;
self.yesterdayLabel.text = [NSString stringWithFormat:#"%#", yesterdaysPrice];
self.changeLabel.text = differenceInPrices;
app.networkActivityIndicatorVisible = NO;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM/dd/yyyy"];
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:#"h:mm:ss aa"];
NSDate *now = [[NSDate alloc] init];
NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];
lstUpdate.text = [NSString stringWithFormat:#"Updated: %# at %#", theDate, theTime];
refreshing = NO;
}];
I also have this code in my viewDidLoad,
[super viewDidLoad];
refreshing = NO;
NSDictionary *save = [[NSUserDefaults standardUserDefaults] objectForKey:#"save"];
if (save) {
int timeStamp = [[save objectForKey:#"day"] intValue];
NSDateComponents *compon = [[NSCalendar currentCalendar] components:(NSUndefinedDateComponent) fromDate:[NSDate date]];
if ([compon day] != timeStamp) {
usingYesterdaysPrices = YES;
yesterdaysPrice = [save objectForKey:#"lastCheckedPrice"];
if (!yesterdaysPrice) {
yesterdaysPrice = #"N/A";
}
}
}
else {
yesterdaysPrice = #"N/A";
}
self.differenceInPrices = #"N/A";
[self sendNewRequest:nil];
[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:#selector(sendNewRequest:) userInfo:Nil repeats:YES];

Unable to either attach or create a .csv file (using CHCSVParser)

I am having a problem either attaching or creating a .csv file in my app, I cannot figure out where the problem exists. In the email view the .csv attachment is shown but when the email is received it has no attachment. I send an array of objects (dataController.masterList) to the CHCSVWriter. I've spent a lot of time this week trying solutions from other questions regarding email attachments and CHCSVWriter and obviously none of the solutions have worked so know I'm asking you. Where does the problem exist, and what do you suggest?
Thank you in advance,
Happy Days, -Rob
- (IBAction)send:(id)sender {
static NSDateFormatter *formatter = nil;
if (formatter == nil) {
formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
}
NSString *filepath = #"testfile.csv";
filepath = [filepath stringByExpandingTildeInPath];
NSOutputStream *exportStream = [NSOutputStream outputStreamToFileAtPath:filepath append:NO];
NSStringEncoding encodingA = NSUTF8StringEncoding;
CHCSVWriter *csvWriter = [[CHCSVWriter alloc] initWithOutputStream:exportStream encoding:encodingA delimiter:','];
[csvWriter writeField:[NSString stringWithFormat:#"One"]];
[csvWriter writeLineOfFields:dataController.masterList];
[csvWriter closeStream];
NSString *path = [[NSBundle mainBundle] pathForResource:filepath ofType:#".csv"];
NSData *mydata = [NSData dataWithContentsOfFile:path];
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
[mail setMailComposeDelegate:self];
[mail setSubject:#"CSV File"];
[mail addAttachmentData:mydata mimeType:#"text/csv" fileName:filepath];
[mail setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
[self presentViewController:mail animated:YES completion:nil];
}
}
- (void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError *)error {
[self dismissViewControllerAnimated:YES completion:nil];
I figured it out, I stopped using the CHCSV writer and just wrote an array then combined the components of the array with a ",".
- (IBAction)send:(id)sender {
static NSDateFormatter *formatter = nil;
if (formatter == nil) {
formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
}
NSIndexPath *index2 = 0;
NSUInteger i = 0;
NSString *holder;
NSArray *holderArray;
NSArray *saverArray;
while (i < dataController.countOfList) {
TimeSheetEntry *sAtIndex = [self.dataController objectInListAtIndex:index2.row];
NSString *dayhold = [formatter stringFromDate:sAtIndex.date];
holderArray = [[NSArray alloc] initWithObjects:sAtIndex.name, sAtIndex.jobnum, sAtIndex.hours, sAtIndex.jobnotes, dayhold, nil];
saverArray = [saverArray arrayByAddingObjectsFromArray:holderArray];
i++;
NSIndexPath *index3 = [NSIndexPath indexPathForRow:i inSection:1];
index2 = index3;
}
holder = [saverArray componentsJoinedByString:#","];//this is the seperating variable
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [paths objectAtIndex:0];
NSString *outputFile = [docDirectory stringByAppendingPathComponent:#"timesheet.csv"];
NSError *csvError = NULL;
BOOL written = [holder writeToFile:outputFile atomically:YES encoding:NSUTF8StringEncoding error:&csvError];
if (!written)
NSLog(#"write failed, error=%#", csvError);
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
[mail setMailComposeDelegate:self];
[mail setSubject:#"CSV File"];
//[mail setMessageBody:holder isHTML:YES];
[mail addAttachmentData:[NSData dataWithContentsOfFile:outputFile] mimeType:#"text/csv" fileName:#"timesheet.csv"];
[mail setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
[self presentViewController:mail animated:YES completion:nil];
}
}
- (void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError *)error {
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
For anyone that still wants to use CHCSVParser, I found that the file path has to be absolute:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Task"
inManagedObjectContext:_tempManagedObjectContext];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *fetchedObjects = [_tempManagedObjectContext executeFetchRequest:fetchRequest error:&error];
NSURL *datapath = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"export.csv"];
NSOutputStream *output = [NSOutputStream outputStreamToMemory];
CHCSVWriter *writer = [[CHCSVWriter alloc] initWithOutputStream:output encoding:NSUTF8StringEncoding delimiter:','];
// Fetch objects to write to .csv
for (Task *task in fetchedObjects) {
[writer writeLineOfFields:#[task.taskID, task.taskTitle, task.taskDescription]];
}
entity = [NSEntityDescription entityForName:#"Journal"
inManagedObjectContext:_tempManagedObjectContext];
[fetchRequest setEntity:entity];
fetchedObjects = [_tempManagedObjectContext executeFetchRequest:fetchRequest error:&error];
for (JournalEntry *entry in fetchedObjects) {
[writer writeLineOfFields:#[entry.day, entry.entryTitle, entry.entryDescription]];
}
[writer closeStream];
NSData *buffer = [output propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
[buffer writeToURL:datapath atomically:NO];

Memory Leak while using NSDateFormatter

I have seen many questions/answers on memory leaks in NSDateFormatter, but none seems to help me determine what is causing memory to leak in my app. Here is my code:
- (id)init
{
if ((self = [super init]))
{
items = [[NSMutableArray alloc] init];
events = [[NSMutableArray alloc] init];
buffer = [[NSMutableData alloc] init];
format = [[NSDateFormatter alloc] init];
lastFromDate = #"";
}
return self;
}
- (void)presentingDatesFrom:(NSDate *)fromDate to:(NSDate *)toDate delegate:(id<KalDataSourceCallbacks>)delegate
{
[format setTimeZone:[NSTimeZone systemTimeZone]];
[format setDateFormat:#"MM/dd/yyyy"];
NSString *stringFromDate = [NSString stringWithString:[format stringFromDate:fromDate]];
NSString *stringToDate = [NSString stringWithString:[format stringFromDate:toDate]];
NSLog(#"From date: %#, To date: %#", stringFromDate, stringToDate);
[self didDatesChange:stringFromDate];
if (dataReady) {
[callback loadedDataSource:self];
return;
}
callback = delegate;
[self retrieveEventData:stringFromDate to:stringToDate];
}
- (void)dealloc
{
[items release];
[events release];
[buffer release];
[lastFromDate release];
[format release];
[super dealloc];
}
When I run "Profile" -> "Leaks", I get a memory leak every time the function is called on line
NSString *stringFromDate = [NSString stringWithString:[format stringFromDate:fromDate]];
Can someone explain what might be going on?
thanks, mike
FYI you can change this:
NSString *stringFromDate = [NSString stringWithString:[format stringFromDate:fromDate]];
to this:
NSString *stringFromDate = [format stringFromDate:fromDate];
stringWithString should return an autoreleased NSString though so I don't believe that is the source of your leak. It looks like there is no leak in your code to me.
you just use bellow method for get string from date its work properly......
-(NSString *)StringFromDate:(NSDate *)DateLocal{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM/dd/yyyy"];
NSString *dateString = [dateFormat stringFromDate:DateLocal];
NSLog(#"Date is HERE =====>> %#",dateString);
return dateString;
}
after when you want to get date string just use like bellow....
NSString *stringFromDate = [self stringFromDate:fromDate]];
[stringfromdate retain];
NSString *stringToDate = [self stringFromDate:toDate]];
[stringTodate retain];
and above -(NSString *)StringFromDate:(NSDate *)DateLocal method is must be define in your viewcontroller.m file....
Its work fine....

Download remote server xml to local(only update is available)

I have an XML file that is going to live on our server. The first time I request an url and download it locally for use within my app. it's working.if the download is available only means we are again go to url and download.
, I compare the local time stamp to the remote file time stamp and only re-download it if the time stamp is newer (e.g. it has been updated).
I am using http post method.If the download is not available i can cancel connection.else..download the server data and update the last modified date to local xml.
Is it correct or any other better way to check
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse httpResponse = (NSHTTPURLResponse)response;
if ([response respondsToSelector:#selector(allHeaderFields)]) {
NSDictionary *dictionary = [httpResponse allHeaderFields];
BOOL check=[self checkUpdate:[[httpResponse allHeaderFields] objectForKey:#"Last-Modified"]];
NSLog(#"%#",[dictionary description]);
if (!check) {
[connection cancel];
[delegate display];
}
}
-(BOOL) checkUpdate:(NSString*) str
{
self.lastmodified=str;
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//
self.cachedPath = [NSString stringWithFormat:#"%#/%#",docDir,self.refxml];
fileManager = [NSFileManager defaultManager];
lastModifiedServer = [[NSDate date] retain];
#try {
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateFormat = #"EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'";
df.locale = [[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"] autorelease];
df.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
[lastModifiedServer release];
lastModifiedServer = [[df dateFromString: self.lastmodified]retain];
[df release];
}
#catch (NSException * e) {
NSLog(#"Error parsing last modified date: %# - %#", self.lastmodified, [e description]);
}
NSDate *lastModifiedLocal = nil;
if ([fileManager fileExistsAtPath:self.cachedPath]) {
NSError *error = nil;
NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:cachedPath error:&error];
lastModifiedLocal = [fileAttributes fileModificationDate];
if ([lastModifiedLocal laterDate:lastModifiedServer] == lastModifiedServer) {
return YES;
}
else
{
return NO;
}
}
else
{
return YES;
}
return YES;
}

Calendar API changing

http://code.google.com/p/scm-subversion/source/browse/trunk/iPhone/CalendarTest/?r=4#CalendarTest%253Fstate%253Dclosed
I am using the above mentioned Calendar API. In CalendarTestViewController.m class we are getting the date. Now I have declared a global variable nsstring type and I want to use that date into another new class by using global variable. I have tried this a number of times but unable to get the output. If anyone know how can I use the selected date by using Calendar API, then please give me some solution.
Thanks in advance.
CODE
- (void)calendarView:(KLCalendarView *)calendarView tappedTile:(KLTile *)aTile{
NSLog(#"Date Selected is %#",[aTile date]);
str=(NSString *)[aTile date];
}
NSLog(#"str:%#",str);
glbdate1 = (NSString *)[aTile date];
NSLog(#"glbdate1:%#",glbdate1);
}
//I have declared the glbdate1 variable globally in app delegate file and i have made the new class calenderview
//I want to display the date in textfield by using global variable. Here is code in calenderview
-(void)viewWillAppear:(BOOL)animated {
if ([glbdate1 length] != 0)
{
from.text = glbdate1;
}
}
You have to convert the NSDate to NSString as follows,
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-mm-dd HH:mm:ss"];
NSString *dateString=[dateFormatter stringFromDate:date];
Then the same NSString value can be converted to NSDate as,
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-mm-dd HH:mm:ss"];
NSDate *dateFromString=[dateFormatter dateFromString:dateString];
-(BOOL)isDateinEventArray:(NSString*)iDateString{
//NSString *searchText = lblDate.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (ToDo *todoObj in appDelegate.todoArray)
{
NSString *date = todoObj.startDate;
[searchArray addObject:date];
}
if ([searchArray count] > 0) {
for (NSString *sTemp in searchArray)
{
NSRange titleResultsRange = [sTemp rangeOfString:iDateString
options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[copyListOfItems addObject:sTemp];
}
[searchArray release];
searchArray = nil;
}
if ([copyListOfItems count] > 0) {
return TRUE;
}else{
return FALSE;
}
}
/*----- Calendar Delegates -----> */
- (void)calendarView:(KLCalendarView *)calendarView tappedTile:(KLTile *)aTile{
NSLog(#"Date Selected is %#",[aTile date]);
// NSString *stringFromDate =
// [[NSString alloc]initWithString:[NSString stringWithFormat:#"%02i-%02i-%i",[aTile.date dayOfMonth],
//
[aTile.date monthOfYear],[aTile.date yearOfCommonEra]]];
NSString *stringFromDate = [[NSString alloc]initWithString:[NSString stringWithFormat:#"%02i-%02i-%02i",[aTile.date yearOfCommonEra],
[aTile.date monthOfYear],[aTile.date dayOfMonth]]];
if([self isDateinEventArray:stringFromDate]){
selectedDate = [aTile date];
eventFoundMsg = #"Events are found on this date.";
eventMsgTag = 1;
}else{
eventFoundMsg = #"No events are found on this date.";
eventMsgTag = 0;
}
[stringFromDate release];
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Event Message"
message:eventFoundMsg
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil]autorelease];
alert.tag = eventMsgTag;
[alert show];
[aTile flash];
/*
if(tile == nil)
tile = aTile;
else
[tile restoreBackgroundColor];
*/
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (eventMsgTag == 1) {
if (buttonIndex == 0)
{
MyToDoView *detailViewController = [[MyToDoView alloc]
initWithNibName:#"MyToDoView" bundle:nil];
detailViewController.searchDate = selectedDate;
NSLog([NSString stringWithFormat:#"%#",detailViewController.searchDate]);
[detailViewController searchDateTableView];
[self.navigationController popViewControllerAnimated:YES];
[detailViewController release];
}
}
}
I hope this can help you....