Unable to get the receive messages in chat screen in xmpp - ios

I am making an app based on chatting i am able to send the messages but unable to recieve messages in my chat screen so can any body help me out
here is my code
if ([[message elementForName:#"body"] stringValue]==nil) {
}
else
{
NSString *messageBody = [[message elementForName:#"body"] stringValue];
XMPPUserCoreDataStorageObject *user = [xmppRosterStorage userForJID:[message from]
xmppStream:xmppStream
managedObjectContext:[self managedObjectContext_roster]];
NSString *displayName = [user displayName];
BOOL isComposing = NO;
NSString *MyString;
NSDate *now = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// [dateFormatter setDateFormat:#"yyyy-MM-dd-HH-mm-ss"];
[dateFormatter setDateFormat:#"HH:mm,yyyy/MM/dd"];
MyString = [dateFormatter stringFromDate:now];
NSLog(#"TIME AND DATE=>%#",MyString);
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
NSString *myJID=[NSString stringWithFormat:#"%##xxxx-mac-mini-2.local",[defaults valueForKey:#"userNameJID"]];
NSString *friendID=[[[message attributeForName:#"from"] stringValue] stringByDeletingLastPathComponent];
NSLog(#"---chatToUserId=>%#",friendID);
if ([message isChatMessageWithBody]){
XMPPUserCoreDataStorageObject *user = [xmppRosterStorage userForJID:[message from]
xmppStream:xmppStream
managedObjectContext:[self managedObjectContext_roster]];
NSString *body = [[message elementForName:#"body"] stringValue];
NSString *displayName = [user displayName];
NSString *msg = [[message elementForName:#"body"] stringValue];
NSString *from = [[message attributeForName:#"from"] stringValue];
// [xmppMessageArchivingStorage archiveMessage:message outgoing:NO xmppStream:xmppStream];
NSMutableDictionary *m = [[NSMutableDictionary alloc] init];
[m setObject:msg forKey:#"msg"];
[m setObject:from forKey:#"sender"];}
in xmpp delegate method that is didReceiveMessage but how can i assign to chat screen class.

You need to learn:
XMPPMessageArchiving is an example module bundled with XMPPFramework which store all incoming and outgoing messages to CoreData-backed database.
NSFetchedResultsController - standard Apple-provided class for feeding data to UITableView or UICollectionView, which you can use as core of "chat screen" class and it will automatically track new messages and update UI.
Sample iPhoneXMPP project have an example of "roster screen" which is backed by UITableView and NSFRC, the only two differences of "chat screen" are:
You need to fetch XMPPMessageArchiving_Message_CoreDataObject entities
You need to specify NSPredicate to fetch only messages related to single "chat", something like bareJid == %# and pass buddy's JID to this predicate

Related

Access NSArray from dictionary

I have a chat application. When I send push notification from the server, it sends me a NSArray value which I use it to forward user profile with NSNumber.
I printed push notification response with alertview and I added response picture. You can see the response of push notification.
I talked about "customDictionary" key. I want to access this '6297' value and after I want to convert to NSNumber.
Here is my code:
#property (nonatomic, copy) NSNumber *userID;
NSArray *array = [[[userInfo valueForKey:#"aps"] valueForKey:#"customDictionary"]array];
NSString *myArrayString = [array description];
NSNumberFormatter *format = [[NSNumberFormatter alloc] init];
format.numberStyle = NSNumberFormatterDecimalStyle;
self.userID = [format numberFromString:myArrayString];
userID is returning null. Is anybody can help me ? Thank you.
I think that the value of key 'customDictionary' is string, try this
NSString *unformattedString = [[userInfo valueForKey:#"aps"] valueForKey:#"customDictionary"];
NSCharacterSet *specialCharSet = [NSCharacterSet characterSetWithCharactersInString:#"[]"];
NSString *newString = [unformattedString stringByTrimmingCharactersInSet:specialCharSet];
NSLog(#"newString : %#",newString);
See your key "aps" give you a dictionary which actually doesn't contain the "customDictionary" key, its outside of your "aps" dictionary. Try the code given below. Good luck!!
NSArray *array = [[userInfo valueForKey:#"customDictionary"] array];
NSString *myArrayString = [array description];
NSNumberFormatter *format = [[NSNumberFormatter alloc] init];
format.numberStyle = NSNumberFormatterDecimalStyle;
self.userID = [format numberFromString:myArrayString];

Method not working on second time through: SVPullToRefresh

So, I've made some progress on my issue described here — https://stackoverflow.com/questions/27348458/svpulltorefresh-infinite-scroll-with-an-rss-feed
Nonetheless, I have a problem. The table loads 10 YouTube videos initially. Then, the second ten will load using
__weak MasterViewController *weakSelf = self;
[self.tableView addInfiniteScrollingWithActionHandler:^{
NSLog(#"Infinite Scroll");
[weakSelf updateVideoList];
}];
-(void) updateVideoList essentially adds 10 items to the array that loads into the table view (reloadData is called on the tableview at the end after addObjectsFromArray adds items to the initial array). This works well enough. The problem is that trying to load a third 10 items does not work. I added the NSLog to see if it even goes into the method a second time, and it doesn't.
Is there any reason for the method to not work a second time?
Edit Here's updateVideoList, but I used the log to determine that the method isn't even called the second time through:
- (void) updateVideoList {
NSString *baseDomain = #"https://gdata.youtube.com/feeds/api/videos";
NSString *maxresults = #"10";
NSString *startIndex = [NSString stringWithFormat:#"%lu", (unsigned long)videoList.count+1];
NSString *orderBy = #"published";
NSString *author = #"theverge";
NSString *extension = #"v=2&alt=jsonc";
NSString *urlYoutube = [NSString stringWithFormat:#"%#?max-results=%#&start-index=%#&orderby=%#&author=%#&%#",
baseDomain,maxresults, startIndex,orderBy,author,extension];
NSDictionary *listOfVideos = [JSONParser listOfVideos:urlYoutube];
int videoListSize = [[[listOfVideos valueForKey:#"data"] valueForKey:#"totalItems"] intValue];
if (videoListSize>0) {
NSMutableArray *secondYoutubeList = [[NSMutableArray alloc] init];
NSArray *arrayVideoList = [[listOfVideos valueForKey:#"data"] valueForKey:#"items"];
for (NSDictionary *videoDictionary in arrayVideoList) {
NSString *idVideo = [videoDictionary valueForKey:#"id"];
NSString *description = [videoDictionary valueForKey:#"description"];
//NSString *updated = [videoDictionary valueForKey:#"updated"];
// NSString *departTimeDate = [videoDictionary valueForKey:#"updated"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
//NSDate *date = [dateFormatter dateFromString:departTimeDate];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];
NSString *updated = [NSString stringWithFormat:#"%ld, %ld, %ld", (long)month,(long)day,(long)year];
NSString *duration = [videoDictionary valueForKey:#"duration"];
NSString *title = [videoDictionary valueForKey:#"title"];
// If we are using wifi, take hqDefault
NSString *thumbnail = [[videoDictionary valueForKey:#"thumbnail"] valueForKey:#"hqDefault"];
YoutubeVideo *video = [[YoutubeVideo alloc] initWithId:idVideo withDescription:description withUpdated:updated withDuration:duration withTitle:title withThumbnail:thumbnail];
[secondYoutubeList addObject:video];
}
[videoList addObjectsFromArray:secondYoutubeList];
[self.tableView reloadData];
}
}
You should call
[self.tableView.infiniteScrollingView stopAnimating];
Once your work of reloading is got completed.

iOS ISO-8583 message sending

I'm an iOS developer. I need to send a message in ISO-8583 standard, via socket server.
I have established connection with server, and it is working well.
The server works this way : when message comes to it in correct format (but with incorrect data, eg. wrong PIN), it responds with proper error code. When message comes in wrong format, the server doesn't respond at all ;)
So, knowing that my connection works fine (tested), I have following problem :
I need to send ISO8583 message to server. The message must have those fields :
SI (2 bytes - size of whole message)
TPDU (it must be 12345 - documetation says)
Detail (more info below)
EOT (specification - sign "0D")
In below example, we are using :
MTI - 0200
Account number - 6019 5300 0601 9592
Code - 700000
Terminal ID - 35959551
PIN - 880088 (needs to have two SPACES appedned to the end (docs says))
Here are documentation specifications :
Field 2 - Card number, length - 19 (3 length + 16 number), format
LLVAR
Field 3 - Processing code, length - 6, format NUMBER
Field 12 - Time (hhmmss), length - 6, format NUMBER
Field 13 - Date (mmdd), length - 4, format NUMBER
Field 41 - Terminal ID, length - 8, format ALPHANUMERICAL
Field 52 - PIN, length - 16, format HEX
So, fields 2,3,12,13,41 and 52 must be set.
I used two methods :
1) using external library : https://github.com/mordoskull/Objective-ISO8583 - using many different combinations of data, it doesn't work. My usage :
ISOMessage *isoMessage1 = [[ISOMessage alloc] init];
NSString *tpdu = #"0102030405";
[isoMessage1 setMTI:#"0200"];
isoMessage1.bitmap = [[ISOBitmap alloc] initWithGivenDataElements:#[#"DE02", #"DE03", #"DE12", #"DE13", #"DE41", #"DE52"] configFileName:nil];
[isoMessage1 addDataElement:#"DE02" withValue:cardNumber configFileName:nil];
[isoMessage1 addDataElement:#"DE03" withValue:#"700000" configFileName:nil];
[isoMessage1 addDataElement:#"DE12" withValue:transactionTime configFileName:nil];
[isoMessage1 addDataElement:#"DE13" withValue:transactionDate configFileName:nil];
[isoMessage1 addDataElement:#"DE41" withValue:#"35959551" configFileName:nil]; //TID - 35959551
[isoMessage1 addDataElement:#"DE52" withValue:#"880088" configFileName:nil];
2) manually setting all fields like this :
//CARD NUMBER
NSData *card = [cardNumber dataUsingEncoding:NSUTF8StringEncoding];
//TPDU
NSMutableData *TPDU = [[NSMutableData alloc] init];
[TPDU appendBytes:"\x01\x02\x03\x04\x05" length:5];
//TRANSACTION CODE
NSData *transactionCode = [[NSString stringWithFormat:#"%x",700000] dataUsingEncoding:NSUTF8StringEncoding];
//TIME AND DATE
NSData *time = [[NSString stringWithFormat:#"%x",[transactionTime intValue]] dataUsingEncoding:NSUTF8StringEncoding];
NSData *date = [[NSString stringWithFormat:#"%x",[transactionDate intValue]] dataUsingEncoding:NSUTF8StringEncoding];
//PIN
NSData *PIN = [[NSString stringWithFormat:#"%# ",self.pinField.text] dataUsingEncoding:NSASCIIStringEncoding];
//TID
NSData *TID = [#"35959551" dataUsingEncoding:NSASCIIStringEncoding];
//MTI
NSMutableData *MTI = [[NSMutableData alloc] init];
[MTI appendBytes:"\x02\x00" length:2];
//BITMAP
NSArray* fields = [NSArray arrayWithObjects:#2, #3,
#12, #13, #41, #52, nil];
NSMutableArray* binary = [NSMutableArray new];
for(int i=0 ; i<64 ; ++i) {
binary[i] = #"0";
}
for(int j = 0; j<[fields count]; ++j)
{
binary[[fields[j] intValue]-1] = #"1";
}
NSMutableString * bitmap = [[NSMutableString alloc] init];
for (NSObject * obj in binary)
{
[bitmap appendString:[obj description]];
}
NSData *bitmapByte = [bitmap dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData *request = [[NSMutableData alloc] init];
[request appendData:TPDU];
[request appendData:MTI];
[request appendData:bitmapByte];
[request appendData:card];
[request appendData:transactionCode];
[request appendData:time];
[request appendData:date];
[request appendData:TID];
[request appendData:PIN];
NSData *SI = [[NSString stringWithFormat:#"00%lu",(unsigned long)[request length]] dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData* fullRequest = [[NSMutableData alloc] init];
[fullRequest appendData:SI];
[fullRequest appendData:request];
I know that Card Number field must have three-digit length appended in front of it, and I know every other specs about ISO8583.
I managed to get NSData that looks like this in Log :
Printing description of fullRequest:
<30303131 39010203 04050200 30313130 30303030 30303031 31303030 30303030 30303030 30303030 30303030 30303030 30303030 31303030 30303030 30303031 30303030 30303030 30303030 30313636 30313935 33303030 36303139 35393261 61653630 31393232 37346231 33353935 39353531 38383030 38382020>
The same message, not converted to NSData, looks like this :
009001020304050200601800000080100001660195300060195927000001131041201359595513838303038382020
And server doesn't respond at all, so I must be sending wrong formatted message.
Can somebody help me how to correctly format the message?
Finally managed to do it myslef. Here is a code for setting the parameters (in case somebody needs it) :
NSDate *currentTime = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//get current Time
[dateFormatter setDateFormat:#"hhmmss"];
NSString *transactionTime = [dateFormatter stringFromDate: currentTime];
transactionTime = [transactionTime stringByReplacingOccurrencesOfString:#":" withString:#""];
//get current Date
[dateFormatter setDateFormat:#"MMdd"];
NSString *transactionDate = [dateFormatter stringFromDate:currentTime];
NSString* cardNumber = [[NSUserDefaults standardUserDefaults] objectForKey:#"cardNumber"];
//TID
NSData *TID = [#"35959551" dataUsingEncoding:NSASCIIStringEncoding];
//PIN
NSData *PIN = [[NSString stringWithFormat:#"%#",self.pinField.text] dataUsingEncoding:NSASCIIStringEncoding];
//TPDU
NSMutableData *TPDU = [[NSMutableData alloc] init];
[TPDU appendBytes:"\x01\x02\x03\x04\x05" length:5];
//MTI
NSMutableData *MTI = [[NSMutableData alloc] init];
[MTI appendBytes:"\x02\x00" length:2];
//TRANSACTION CODE
NSString *transactionCode = #"700000";
NSData *trCode = [self convertToData:transactionCode];
//CARD NUMBER
NSString *cardWithLength = [#"16" stringByAppendingString:cardNumber];
NSData *card = [self convertToData:cardWithLength];
//TIME AND DATE
NSData *time = [self convertToData:transactionTime];
NSData *date = [self convertToData:transactionDate];
//BITMAP
NSString *mapa = #"6018000000801000";
NSData *mapaData = [self convertToData:mapa];
NSMutableData *request = [[NSMutableData alloc] init];
[request appendData:TPDU];
[request appendData:MTI];
[request appendData:mapaData];
[request appendData:card];
[request appendData:trCode];
[request appendData:time];
[request appendData:date];
[request appendData:TID];
[request appendData:PIN];
NSString *SI = [NSString stringWithFormat:#"00%lu",(unsigned long)[request length]];
NSData *SIData = [self convertToData:SI];
NSMutableData* fullRequest = [[NSMutableData alloc] init];
[fullRequest appendData:SIData];
[fullRequest appendData:request];

Fetching data from SQLite and want to get only the last value of column id

I am fetching data from SQLite and want to get only the last value of column id in XCode.The code is
NSString *selquery = #"select id from watchlists";
if (self.uid != nil) {
self.uid = nil;
}
self.uid = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:selquery]];
NSString *valvar;
valvar = [_uid lastObject];
NSNumber *custval = [_uid valueForKey: #"#lastObject"];
NSString *imgval1 = [NSString stringWithFormat:#"%#_%s",custval,"1"];
NSLog(#"%#", imgval1);
Please tell me how can I get only the value because by using the above code I am getting array with last value of id.
I think this your case, try this it maybe help you
NSArray *temp=[NSArray arrayWithObjects:#"1",#"2",#"3", nil];
NSArray *temp0ne=[[NSArray alloc]initWithArray:temp];
// NSString *tmmp=[temp0ne lastObject];
NSArray *finalStr=[uid lastObject];
NSLog(#"Dictionary is---->%#",[finalStr lastObject]);
Output:
3_1
EDIT
NSArray *temp=[NSArray arrayWithObjects:#"(1)",#"(2)",#"(3)", nil];
NSArray *temp0ne=[[NSArray alloc]initWithArray:temp];
NSString *tmmp=[temp0ne lastObject];
NSString *final=[tmmp stringByReplacingOccurrencesOfString:#"(" withString:#""];
final=[final stringByReplacingOccurrencesOfString:#")" withString:#""];
NSString *imgval1 = [NSString stringWithFormat:#"%#_%s",final,"1"];
NSLog(#"%#", imgval1);
I don't know is this correct way or not try this....otherwise have look this link
I don't fully understand your code structure hehe. Try this:
NSString *selquery = #"select id from watchlists";
if (self.uid != nil) {
self.uid = nil;
}
self.uid = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:selquery]];
NSNumber *custval = [_uid objectAtIndex:[_uid count]-1];
*
NSString *str = [NSString stringWithFormat#"%#",custval];
str = [str stringByReplacingOccurrencesOfString:#"("
withString:#""];
NSString *finalCustval = [NSString stringWithFormat#"%#",str];
finalCustval = [finalCustval stringByReplacingOccurrencesOfString:#")"
withString:#""];
*
NSString *imgval1 = [NSString stringWithFormat:#"%#_%s",finalCustval ,"1"];
NSLog(#"%#", imgval1);
UPDATE
try adding the ones with *.

Log Accelerometer data to a file on Iphone IOS

Hi I am trying to write to a file from the accelerometer data. Here is my code:
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
//xax.text = [NSString stringWithFormat:#"X:[%2.6f]",acceleration.x];
//yax.text = [NSString stringWithFormat:#"Y:[%2.6f]",acceleration.y];
//zax.text = [NSString stringWithFormat:#"Z:[%2.6f]",acceleration.z];
NSString *acc_x = [[NSString alloc] initWithFormat:#"X:[%2.6f]",acceleration.x];
NSString *acc_y = [[NSString alloc] initWithFormat:#"Y:[%2.6f]",acceleration.y];
NSString *acc_z = [[NSString alloc] initWithFormat:#"Z:[%2.6f]",acceleration.z];
xax.text = acc_x;
yax.text = acc_y;
zax.text = acc_z;
[acc_x release];
[acc_y release];
[acc_z release];
//wfm == 2 //Initialization of Appending to the file
if (wfm == 2)
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *txtFileName = [[NSString alloc] initWithFormat:#"tmp/%#.txt",txtName.text];
NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:txtFileName];
//NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:#"tmp/acc_w_trial2.txt"];
//Current Contents of the file
NSString *fileCurrent = [[NSString alloc] initWithContentsOfFile:fileName];
//Date and Time of each Accelerometer Data
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd 'at' HH:mm:ss:SSS"];
NSDate *date = [NSDate date];
NSString *formattedDateString = [dateFormatter stringFromDate:date];
NSString *msg = [[NSString alloc] initWithFormat:#"%#%# %#%#%# \n",fileCurrent,formattedDateString,xax.text,yax.text,zax.text];
//Convert NSstring to NSData
NSData* data=[msg dataUsingEncoding: [NSString defaultCStringEncoding]];
//bool fileCreationSuccess = [fileManager createFileAtPath:fileName contents:data attributes:nil];
[fileManager createFileAtPath:fileName contents:data attributes:nil];
[msg release];
[dateFormatter release];
[fileCurrent release];
[txtFileName release];
}
}
I get the warning level 1 and level 2. Is there a way I can release the NSFileManager memory to prevent this from locking up?
Your handler method to collect accelerometer data seems not very performant. You are allocating the resources (memory, file) everytime which can take a long time.
You should allocate the needed resources only once (i.e. use dispatch_once) and keep the file open. Use a NSFileHandle (method fileHandleForWritingAtPath) in order to append the data at the end of the file.
Furthermore NSHomeDirectory() is not where you're supposed to save user data, as iOS apps are sandboxed.
Either use NSTemporaryDirectory() or write in the Documents or Library Folder. The following is from Apple's sample code, usually in application delegate class:
- (NSString *)applicationDocumentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
You can try using an Autorelease Pool.

Resources