How To get Sender E-mail from Device? - iphone

I am sending some data from my application to server. my data consist of different fields as my code shown below
-(void)createXML
{
xmlStr = #"<?xml version='1.0'?>\n<jand_req>\n<inquiryList>\n<productArr>\n";
NSString *nameStr=[NSString stringWithFormat:#"<name>%#</name>\n",name.text];
xmlStr=[xmlStr stringByAppendingString:nameStr];
NSString *compNameStr=[NSString stringWithFormat:#"<comp_name>%#</comp_name>\n",compName.text];
xmlStr=[xmlStr stringByAppendingString:compNameStr];
NSString *cityStr=[NSString stringWithFormat:#"<city>%#</city>\n",city.text];
xmlStr=[xmlStr stringByAppendingString:cityStr];
NSString *countryStr=[NSString stringWithFormat:#"<country>%#</country>\n",[nameToCode objectForKey:country.text]];
xmlStr=[xmlStr stringByAppendingString:countryStr];
NSString *commentsStr=[NSString stringWithFormat:#"<comment>%#</comment>\n",commentsBox.text];
xmlStr=[xmlStr stringByAppendingString:commentsStr];
xmlStr=[xmlStr stringByAppendingString:#"</userDetail>\n</inquiryList>\n</jand_req>"];
}
After this i send the above data to server as my code shown below
- (void)submitForm
{
[self createXML];
NSLog(#"myaccesscode%#",[fn getValFromSettings:#"accessCode"]);
NSString *serviceUrlStr=[NSString stringWithFormat:#"%#/%#/API_sendmail.php?access_code=%#",domainName,apiFolderPath,[fn getValFromSettings:#"accessCode"]];
NSLog(#"%#",serviceUrlStr);
NSURL * serviceUrl = [NSURL URLWithString:[serviceUrlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest * serviceRequest = [NSMutableURLRequest requestWithURL:serviceUrl cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:100];
[serviceRequest setValue:#"text/xml" forHTTPHeaderField:#"Content-type"];
[serviceRequest setHTTPMethod:#"POST"];
[serviceRequest setHTTPBody:[xmlStr dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *conn=[[[NSURLConnection alloc] initWithRequest:serviceRequest delegate:self startImmediately:YES] autorelease];
}
All the above code works fine for me but now i want to include an another feature in this code Which consist of sender E-mail address but this sender E-mail must be fetch from device same as when we use MFMailComposeViewController in application then automatically it gets sender E-mail Address from Device.Any help will be appriated thanks.

#import <AddressBook/AddressBook.h>
NSString *emailAddr = #"";
ABPerson *aPerson = [[ABAddressBook sharedAddressBook] me];
ABMultiValue *emails = [aPerson valueForProperty:kABEmailProperty];
if([emails count] > 0)
emailAddr = [emails valueAtIndex:0];
don't forget to add AddressBook.framework.
Now, the emailAddr contains the senders email which you can append to your xml string or wherever you want it to!
-(void)createXML
{
// Your code
NSString *emailStr=[NSString stringWithFormat:#"<email>%#</email>\n",emailAddr];
xmlStr=[xmlStr stringByAppendingString:emailStr];
}
happy coding!

Related

NSMutableRequest and Flickr API for upload images

I use Flickr API for my app to manage user's photo. I decided to make authentication using Apple's classes and it works fine for me. Now my app is authenticated and has all necessary tokens and secret keys so it's possible to perform GET requests with authentication for methods like flickr.photos.search, flickr.test.login and so on.
But I spent a few days trying to perform upload using http://api.flickr.com/services/upload/
and their instructions here.
They say that request should have argument 'photo' and this parameter should not be included in the signature. That is clear, but I have no idea how to implement this parameter the request.
#import "FlickrUploader.h"
#import "HMACSH1.h"
#import "Prefs.h"
#import "NSString+URLEncode.h"
#implementation FlickrUploader
- (void)uploadPhotoAtPath:(NSString*)filePath {
NSString *upload_api_url = #"http://api.flickr.com/services/upload/";
NSString *oauth_nonce = [NSString stringWithFormat:#"%d", 10000000 + arc4random()%1000000];
NSString *oauth_timestamp = [NSString stringWithFormat:#"%d", (long)[[NSDate date] timeIntervalSince1970]];
NSString *oauth_consumer_key = CONSUMER_KEY;
NSString *oauth_signature_method = #"HMAC-SHA1";
NSString *oauth_version = #"1.0";
NSString *oauth_token = [[NSUserDefaults standardUserDefaults] objectForKey:OAUTH_ACCESS_TOKEN_KEY];
//creating basestring to make signature without a 'photo' argument according to API
NSMutableString *basestring = [[NSMutableString alloc] initWithCapacity:8];
[basestring appendFormat:#"&oauth_consumer_key=%#",oauth_consumer_key];
[basestring appendFormat:#"&oauth_nonce=%#",oauth_nonce];
[basestring appendFormat:#"&oauth_signature_method=%#",oauth_signature_method];
[basestring appendFormat:#"&oauth_timestamp=%#",oauth_timestamp];
[basestring appendFormat:#"&oauth_token=%#", oauth_token];
[basestring appendFormat:#"&oauth_version=%#",oauth_version];
//this is may class to make HMAC-SHA1 signature (it works for authentication and for GET requests)
HMACSH1 *hMACSH1 = [[HMACSH1 alloc] init];
NSMutableString *urlEncodedBaseString = [[NSMutableString alloc] initWithCapacity:3];
[urlEncodedBaseString appendString:#"POST"];
[urlEncodedBaseString appendFormat:#"&%#",[upload_api_url urlEncodedString]];
[urlEncodedBaseString appendFormat:#"&%#",[basestring urlEncodedString]];
NSString *oauth_token_secret = [[NSUserDefaults standardUserDefaults] objectForKey:OAUTH_TOKEN_SECRET_KEY];
NSString *hash_key = [CONSUMER_SECRET stringByAppendingFormat:#"&%#",oauth_token_secret];
NSString *oauth_signature = [hMACSH1 hmacSH1base64ForData:urlEncodedBaseString keyValue:hash_key];
//creating url for request
NSMutableString *urlString = [[NSMutableString alloc] initWithCapacity:8];
[urlString appendFormat:#"%#",upload_api_url];
[urlString appendFormat:#"?"];
[urlString appendString:basestring];
[urlString appendFormat:#"&oauth_signature=%#", oauth_signature];
NSURL *authURL = [[NSURL alloc] initWithString:urlString];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:authURL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
request.HTTPMethod = #"POST";
UIImage *img = [UIImage imageNamed:filePath];
NSData *imgData = UIImageJPEGRepresentation(img, 0.8);
//here I don't know what to do :((( perhaps NSOutputStream
}

data from iPhone to php

i have this in Xcode:
NSString *post =[[NSString alloc] initWithString:#"message";
this string i want to send to myadress.php. anybody help me with some good reference or code please.
this is my php side:
<?
$connect = mysql_connect ("$dbserver", "$dbuser", "$dbpass");
mysql_select_db("$dbname") or die(mysql_error());
$feed = $_GET['feed_message'];
$login = mysql_query("INSERT INTO feedback SET feed_message ='".$feed."'", $connect) or die(mysql_error());
mysql_close($connect);
?>
You can try this and you need implement the NSURLConnection delegate method
NSURL *url = [NSURL URLWithString:#"http://yoururl"];
NSURLRequest *urlReq = [NSURLRequest requestWithURL:url];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:urlReq delegate:self];
[connection start];
You can also use ASIHttpRequest, it has more Features.
In fact you just want to send a request to specific URL containing parameter "feed_message":
http://myserver.com/myscrypt.php?feed_message=message
To do it you need:
a. Create an url:
NSString * scriptURLString = #"http://myserver.com/myscrypt.php";
NSString * parameterName = #"feed_message";
NSString * post = #"message";
NSString * urlString = [NSString stringWithFormat:#"%#?%#=%#",scriptURLString, parameterName, post];
NSURL * url = [NSURL URLWithString:urlString];
b. send request to url. There are many ways to do it depending on your needs.
You may send asynchronous request (set delegate property and implement delegate methods to handle results)
[NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url] delegate:nil];
or simply use NSData synchronous method:
[NSData dataWithContentsOfURL:url];

How to avoid URL NOT SUPPORTED error on iphone

I am calling a URL through POST HTTP method. When I am not connected to 3G or WiFi, it will never fetch the URL correctly and will never get the response from the URL correctly.
Connection is made through post:
NSString *URL = [NSString stringWithFormat:#"http://www.abc.com/webservices/client_server.cfc];
[[NSURLCache sharedURLCache] removeAllCachedResponses];
NSString *time_stamp =[NSString stringWithFormat:#"time_stamp=%#", self.today];
NSData *postData = [time_stamp dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *URLRequest = [[[NSMutableURLRequest alloc] init] autorelease];
[URLRequest setURL:[NSURL URLWithString:URL]];
[exhURLRequest setHTTPMethod:#"POST"];
[URLRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[URLRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[URLRequest setHTTPBody:postData];
self.connection =[[[NSURLConnection alloc] initWithRequest:URLRequest delegate:self] autorelease];
NSAssert(self.connection != nil, #"Failure to create URL connection.");
I am checking if I get the response through :
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// check for HTTP status code for proxy authentication failures
// anything in the 200 to 299 range is considered successful
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (([httpResponse statusCode]/100) == 2) {
self.data = [NSMutableData data];
} else {
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:
NSLocalizedString(#"HTTP Error",
#"Error message displayed when receving a connection error.")
forKey:NSLocalizedDescriptionKey];
NSError *error = [NSError errorWithDomain:#"HTTP" code:[httpResponse statusCode] userInfo:userInfo];
[self handleError:error];
}
}
But some how when the URL is not connected lets say when I am in the metro or something, I cannot connect to URL and it throws me "URL NOT SUPPORTED". How can I avoid such a scenario and allow the app to push forward without throwing such an error ? If anybody has used offline redirection to the app without keep on waiting the user on the front screen.
Download apple’s Reachability sample code. Add Reachability.h+.m to your project. Link SystemConfiguration framework. Then use their Reachability class like so.
#import "Reachability.h"
for WiFi:
-(void)doStuff{
Reachability *wifi = [Reachability reachabilityForLocalWiFi];
if (wifi.currentReachabilityStatus == ReachableViaWiFi){
// do connected stuff
}
else {
// do offline stuff
}
}
For Wifi or 3G:
-(void)doStuff{
NetworkStatus connectivity = [Reachability reachabilityForInternetConnection].currentReachabilityStatus;
if (connectivity == ReachableViaWiFi || connectivity == ReachableViaWWAN){
// do connected stuff
}
else {
// do offline stuff
}
}
If you will be continually doing network tasks add the reachability object to your class. That will improve performance and allow you to use it's notifier.
some time this "URL NOT SUPPORTED error" is due to the url not encoding.
for this encode url by using this.or there are lots of ways on internet.
dont encode whole url or base url (as it will encode ":" and '/' too and it may cause errors)
only special charecter needs to be encode like &,# etc.
NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)pathRequest,
NULL,
(CFStringRef)#"!*'();:#&=+$,%#[]",
kCFStringEncodingUTF8 ));
How to check for an active Internet connection on iOS or OSX?
Use the solution propsed here to avoid sending a request when you don't have an active internet connection. Simple.

Ampersand in POST request causing havoc

I have a simple POST coming from my iphone app. Its working fine, except passing an ampersand causes the backend to break - it's almost like its treating it like a GET request (ampersands seperate the variable names). Do I need to do some kind of encoding first? Here is the code:
NSString *content = [[NSString alloc] initWithFormat:#"data=%#&email=%#", str, emailAddress.text];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://www.myurl.com/myscript.php"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[content dataUsingEncoding:NSISOLatin1StringEncoding]];
// generates an autoreleased NSURLConnection
[NSURLConnection connectionWithRequest:request delegate:self];
I had this issue in iOS7 and the accepted answer didn't work at all (actually, that is my standard when sending data to the backend). The ampersand was breaking in the backend side, so I had to replace the & by %26. The backend was being done in python and the code was legacy and was using ASI.
Essentially I have done the following:
NSString *dataContent = [NSString stringWithFormat:#"text=%#",
[json stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
dataContent = [dataContent stringByReplacingOccurrencesOfString:#"&"
withString:#"%26"];
ByAddingPercent....... will not work as & is a valid URL character.
I needed to send a JSON with & in it, it is the same idea though;
NSString *post = [NSString stringWithFormat:#"JSON=%#", (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)jsonString, NULL, CFSTR(":/?#[]#!$&’()*+,;="), kCFStringEncodingUTF8))];
"jsonString" towards the end is what is converted.
Edit: As stringByAddingPercentEscapesUsingEncoding: should be used to encode parts of the query, not the whole one, you should be using another method instead.
Unfortunately, Foundation doesn't provide such a method, so you need to reach to CoreFoundation:
- (NSString *)stringByURLEncodingString:(NSString *)string {
return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(
kCFAllocatorDefault,
(__bridge CFStringRef)string,
NULL, // or (__bridge CFStringRef)(#"[].")
(__bridge CFStringRef)(#":/?&=;+!##$()',*"),
kCFStringEncodingUTF8
);
}
You can use
- stringByAddingPercentEscapesUsingEncoding:
In your case it will look like this:
NSString * content = [[NSString alloc] initWithFormat:#"data=%#&email=%#", [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], [emailAddress.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
You can do this in this way, too:
NSString *dataStr = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *emailStr = [emailAddress.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *content = [[NSString alloc] initWithFormat:#"data=%#&email=%#", dataStr, emailStr];
I'm not sure if this will work in your case, but you could try %38 to try and encode the ampersand.

iphone: NSMutableURLRequest returns strange characters for MS Word style apostrophe

We are pulling content off our website using XML/NSMutableURLRequest and sometimes it pulls through the "curly" style apostrophe and quotes, ’ rather than '. NSMutableURLRequest seems to hate these and turns them into the strange \U00e2\U0080\U0099 string.
Is there something that I can to do prevent this? I am using the GET method, so should I be somehow telling it to use UTF-8? Or, am I missing something?
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = YES;
NSString *urlStr = [NSString stringWithFormat:#"%#",url];
NSURL *serviceUrl = [NSURL URLWithString:urlStr];
NSMutableURLRequest *serviceRequest = [NSMutableURLRequest requestWithURL:serviceUrl];
[serviceRequest setHTTPMethod:#"GET"];
NSURLResponse *serviceResponse;
NSError *serviceError;
app.networkActivityIndicatorVisible = NO;
return [NSURLConnection sendSynchronousRequest:serviceRequest returningResponse:&serviceResponse error:&serviceError];
NSURLConnection returns an NSData response. You can take that NSData response and turn it into a string. Then take this string, turn it back into a NSData object, properly UTF-8 encoding it along the way, and feed it to NSXMLParser.
Example: (Assuming response is the NSData response from your request)
// long variable names for descriptive purposes
NSString* xmlDataAsAString = [[[NSString alloc] initWithData:response] autorelease];
NSData* toFeedToXMLParser = [xmDataAsAString dataUsingEncoding:NSUTF8StringEncoding];
NSXMLParser* parser = [[[NSXMLParser alloc] initWithData:toFeedToXMLParser] autorelease];
// now utilize parser...
I would suggest replacing those characters using stringByReplacingCharactersInRange:withString: to replace the unwanted strings.
NSString *currentTitle = #"Some string with a bunch of stuff in it.";
//Create a new range for each character.
NSRange rangeOfDash = [currentTitle rangeOfString:#"character to replace"];
NSString *location = (rangeOfDash.location != NSNotFound) ? [currentTitle substringToIndex:rangeOfDash.location] : nil;
if(location){
currentTitle = [[currentTitle stringByReplacingOccurrencesOfString:location withString:#""] mutableCopy];
}
I've done this in the past to handle the same problem you describe.
Try using the stringByReplacingPercentEscapesUsingEncoding: