Objective c,Get MailCore CTCoreMessage attachments - attachment

I'm trying to get the attachments of a Mail with MailCore but it's always empty. My code is
[myAccount connectToServer:#"imap_server" port:143 connectionType:CONNECTION_TYPE_PLAIN authType:IMAP_AUTH_TYPE_PLAIN login:#"username" password:#"password"];
CTCoreFolder *inbox = [myAccount folderWithPath:#"INBOX"];
NSSet *messageSet = [inbox messageObjectsFromIndex:1 toIndex:0];
NSEnumerator *objEnum = [messageSet objectEnumerator];
id msg;
while(msg = [objEnum nextObject]) {
[msg fetchBody];
NSArray *atts=[msg attachements];
//Do something with atts
}
but the atts is always empty!Somebody please tell me why??I am sure there are two attachments in the newst mail message,and I can even get some infomation through [msg render] method,but it is not what I want.

You first need to call fetchBody or fetchBodyStructure on the message. something like:
[msg fetchBody];

Related

Corruption of NSString or encoding issue in Objective C

Please see code below:
+ (void)splashDataFromJSON:(NSData *)objectNotation error:(NSError **)error
{
NSError *localError = nil;
NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:objectNotation options:0 error:&localError];
if (localError != nil) {
*error = localError;
}
NSMutableArray* btms = [[NSMutableArray alloc] init];
NSMutableDictionary* btmManufacturerResolutionDictionary = [[BTMCache sharedManager] btmManufacturerResolutionDictionary];
NSArray *results = [parsedObject valueForKey:#"results"];
NSLog(#"Count %d", parsedObject.count);
NSString* imageBaseUrl = [[parsedObject valueForKey:#"general"] valueForKey:#"image_base_url"];
imageBaseUrl = [imageBaseUrl stringByAppendingString:#"hdpi/"];
NSString* splashImageName = [[[parsedObject valueForKey:#"general"] valueForKey:#"splash"] valueForKey:#"img"];
NSString* splashAdvertiserURL = [[[[parsedObject valueForKey:#"general"] valueForKey:#"splash"] valueForKey:#"url"] copy];
NSMutableString* appendedString = [[NSMutableString alloc] init];
for(int i =0 ;i<[splashAdvertiserURL length]; i++) {
char character = [splashAdvertiserURL characterAtIndex:i];
printf(&character);
sleep(0.1);
if (character != "!")
{
[appendedString appendFormat:#"%c", character];
}
}
[[SplashData sharedManager] setSplashAdvertiserURL:appendedString];
[[SplashData sharedManager] setSplashImageName:splashImageName];
splashAdvertiserURL = [[SplashData sharedManager] splashAdvertiserURL];
}
The point of interest is in splashAdvertiserURL. When I receive this data and print it out using po, it comes out as "https://radar.com/ref/go/84/". This is fine and what was expected. When I look at the incoming data in JSONLint it looks like this:
"general": {
"image_base_url": "https:\/\/radar.com\/img\/manufacturers\/",
"splash": {
"img": "image1.png",
"url": "https:\/\/radar.com\/ref\/go\/84\/"
}
},
As you can see, further on I put the NSString into a singleton with an NSString property. Nothing abnormal here. I then proceed to retrieve it to see that all is ok. Further to this the program continues. In another class I wish to retrieve this information, and when I try and do that, it throws EXC_BAD_ACCESS. There appears to be garbage in there.
I then put in a loop in the code as you can see to print out the characters one at a time. Very curiously, when I print that out using po I get:
https://
r
a
d
ar.com/ref/go/8 4!/"
Exactly in that format. If I then proceed to hardcode the string https://radar.com/ref/go/84/ - including escape characters and everything, then all works fine. No issues. If I handle a normal string incoming without escape characters it stores fine in the singleton as well, no issue. enter code here
I am pretty stumped here as to what is going on. Can someone assist?
Thank you
For URL you received as string you need to encode before use it to in your app. Have a look at below code:
NSString *sampleUrl = #"https:\/\/radar.com\/ref\/go\/84\/";
NSString *encodedUrl = [sampleUrl stringByAddingPercentEscapesUsingEncoding:
NSUTF8StringEncoding];

NSString stringWithFormat objectForKey custom Json data

This code shows my user's username in a UILabel named caption
caption.text = [NSString stringWithFormat:#"#%#",[data objectForKey:#"username"]];
I want caption to instead show that user's device token instead of their username. This is how the device token has been used successfully in the app so far.
//A different Method that successfully handles the device token
NSMutableDictionary* params =[NSMutableDictionary dictionaryWithObjectsAndKeys:command, #"command", [_dataModel deviceToken], #"token", nil ];
&
//Another different method that successfully handles the device token with a slightly different syntax
NSDictionary *params = #{#"cmd":#"join",
//the red text passes user_id to _datamodels userId method and thusly to api.php's handleJoin function
#"token":[_dataModel deviceToken],
};
Question: how can one write the correct syntax to show the token, as is, for the objectforkey value? This is what I've tried but I get a compiler warning: no visible interface declaration for selector objectForKey. I know this can be done, how?
caption.text = [NSString stringWithFormat:#"#%#",[data objectForKey:#"token":[_dataModel deviceToken]]];
Original j son : data
//Method body
-(id)initWithIndex:(int)i andData:(NSDictionary*)data
{
self = [super init];
if (self !=nil)
{
Try this one:
caption.text = [NSString stringWithFormat:#"%#", data[#"username"][#"token"]];
i think this will solve your problem
caption.text = [NSString stringWithFormat:#"%#",[params valueForKey:#"token"]];

Getting %20 in twitter private message

Hi here is my code for sending private message to twitter follower/followings,message has been sent but problem is followers are getting message string with %20
-(void)PostOnTwitter :(NSArray *)ParamArray
{
NSLog(#"ParamArray===%#",ParamArray);
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
{
if(!accountStore)
accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error)
{
if(granted!=0)
{
NSArray *twitterAccounts = [self.accountStore accountsWithAccountType:accountType];
NSURL *MsgUrl=[NSURL URLWithString:#"https://api.twitter.com/1.1/direct_messages/new.json"];
NSDictionary *Msgparams = #{#"screen_name" : [ParamArray objectAtIndex:0], #"text" :
[[ParamArray objectAtIndex:1]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] };
SLRequest *Msgrequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:MsgUrl parameters:Msgparams];
[Msgrequest setAccount:[twitterAccounts lastObject]];
[Msgrequest performRequestWithHandler:^(NSData *responseData,NSHTTPURLResponse *urlResponse,NSError *error) {
if (responseData) {
if (urlResponse.statusCode >= 200 && urlResponse.statusCode < 300) {
NSError *jsonError;
NSDictionary *timelineData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&jsonError];
if (timelineData) {
[self performSelectorOnMainThread:#selector(CardHasSent) withObject:nil waitUntilDone:NO];
}
}
}
}];
}
}];
}
}
My followers are getting private message like
user%20has%20sent%20you%20a%20card%20from%20happy%20heART%20cards.%20http://www.happyheartcards.net/o.php?t=ODYw
How can I send proper text?Please help.
I think probelm is stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding,but if I don't use NSUTF8StringEncoding message sending fails.
ParamArray has not been encoded earlier ParamArray===(
jry088,
"user has sent you a card from happy heART cards. http://www.happyheartcards.net/o.php?t=OTA1"
)
%20 is indeed the string escape for a space character, and this is the correct behaviour that you are requesting in using stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding. However, the Twitter API does want POST data for direct messages encoded like this:
https://dev.twitter.com/docs/api/1.1/post/direct_messages/new
I thought the most likely thing therefore was that you were running the encoding twice, which would mean that your % in %20s are getting re-encoded to say "Hey, I really mean a percentage sign here.
When I look at the code, there are multiple redundant calls to [ParamArray objectAtIndex:1] and earlier re-encoding of the string data into UTF8:
NSString *StringData = [ParamArray objectAtIndex:1];
const char *cString = [StringData UTF8String];
NSString *Datastringone = [NSString stringWithFormat:#"%s",cString];
NSString *str = [ParamArray objectAtIndex:1];
None of these variables or this processing ever gets used. This made me wonder whether the string in the ParamArray has already been encoded into UTF8 in an earlier part of your application, so that you are encoding it for the second time when you pass it in here.
NSDictionary *Msgparams = #{#"screen_name" : [ParamArray objectAtIndex:0], #"text" :
[[ParamArray objectAtIndex:1]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] };
EDIT
Actually, I'm going to return to what I originally posted, before I updated the above. I think you're actually getting exactly what you ask for with that encoded text, and the question shouldn't be why you're getting %20s in your text, but rather why the code you've got now is accepting a DM whereas it was failing after all.
If you look at the API reference I linked above (https://dev.twitter.com/docs/api/1.1/post/direct_messages/new) it shows the POST data as % encoded earlier on, but if you actually look at the full code example of what is to be submitted, the string isn't actually encoded at all:
94 "text": "hello, tworld. welcome to 1.1."
So first—change as little else as possible, but remove the encoding stage, and confirm that you still can't send a DM. It could be that you fixed something else without realising it and that is why the POST started working. This would obviously be helped by not embedding the encoding stage into the creation of the dictionary. You get much more readable code if you create all the values separately and then pass the final encoded and prepared variables in when you create the dictionary. A few more temporary variables or pointers may be created but that's well worth it for the increased readability of the code. :)

Can't retrieve XMPP JID from NSMutableDictionary iOS app.

When I receive XMPP Presence in the app , I am adding its contents to a NSMutableDictionary to send it across another ViewController.If I use NSLog to see the contents of this dictionary , I can see everything fine.But when I access this NSMutableDictionary from another ViewController I can't find the JID.Rest of the things are stored fine.
This is what I am doing while storing the XMPP Presence contents i e JID and Name.
- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence
{
NSString *fromUser = [[presence from]user]; //name of user
NSString *fromUserJID = [NSString stringWithFormat:#"%#",[presence from]] ;
NSLog(#"presence from user JID :- %#", fromUserJID); // This shows the JID.
[_locationDictionary setObject:fromUser forKey:#"fromUser"];
[_locationDictionary setObject:fromUserJID forKey:#"fromJID"];
NSLog(#"locationary dictionary :- %#",_locationDictionary ); // This shows name as well as JID.
// add to array
[_presenceArray addObject:_locationDictionary];
Now when I am trying to access this in another ViewController I do this:-
NSString *str=view.annotation.title; //This has the name of the user.
NSLog(#"annotation title :- %#", str);
for (NSDictionary *obj in appDelegate.presenceArray)
{
NSString *titleString = [obj objectForKey:#"fromUser"];
if ([str isEqualToString:titleString]) //for the same username I need the JID
{
NSString *jidString = [obj objectForKey:#"fromJID"];
[ dict setObject:jidString forKey:#"jid"]; //dict is NSMutableDictionary
NSLog(#"retrieved jid is :- %#", dict); // THIS IS NULL
[presence from] will give XMPPJid which is NSObject type.
XMPPJID *jid = [presence from];
Try to get Jid string this way
NSString *fromUserJID = [[presence from] full];//Will give Jid have user, resource, domain
//OR
NSString *fromUserJID = [presence fromStr]; //Only give Jid of user.

How to get user interests from the native iOS Facebook SDK?

I've been reading through the documentation, and I couldn't find anything. For other properties like name, id, etc, they're available in the FBGraphUser class. What I need though is the interest list for the user. I believe I have to use the FBGraphObject class, but I'm not really sure how to go about doing so. Any guidance would be very appreciated. Thanks!
me/interests is how you get the interests of the user. if you're looking for someone else, like the user's friend, then id/interests
This counts on the user being signed in
-(void)fbRequest{
[FBRequestConnection startWithGraphPath:#"me/interests" completionHandler:^(FBRequestConnection *connection,NSDictionary<FBGraphObject> *result,NSError *error){
if(!error){
NSArray *data = [result objectForKey:#"data"];
[self updateInterests:data];
}else{
}
}];
}
-(void)updateInterests:(NSArray*)interests
{
NSString *str = self.groupList.text;
for(FBGraphObject <FBGraphUser>*interest in interests) //Using FBGraphUser because it implements name though I'd love to use something else
{
str = [str stringByAppendingFormat:#"%#\n",interest.name ];
}
[self.groupList setText:str];
}
an alternative to the above method does not rely on the coincidence that graphuser has name, so here it is
-(void)updateInterests:(NSArray*)interests
{
NSString *str = self.groupList.text;
for(FBGraphObject *interest in interests) //Using FBGraphUser because it implements name though I'd love to use something else
{
str = [str stringByAppendingFormat:#"%#\n",[interest objectForKey:#"name"] ];
}
[self.groupList setText:str];
}

Resources