I need to send a cookie in the request. But seems the cookie is not send. What is wrong I am doing here,
// set the cookie for getdoc request url
if (request.cookie)
{
NSDictionary *cookieProperties = #{NSHTTPCookieName : #"GetDoc",
NSHTTPCookieValue : request.cookie,
NSHTTPCookieDomain : [NSURL URLWithString:request.url].host,
// NSHTTPCookieOriginURL: request.url,
NSHTTPCookiePath : #"/",
// NSHTTPCookieVersion : #"1",
NSHTTPCookieExpires : [[NSDate date] dateByAddingTimeInterval:60*60*24*30]
};
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
// NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig];
NSURLSession *session = [NSURLSession sharedSession];
__block NSData *documentData = nil;
__block NSString *mimeType = nil;
DLog(#"COOKIES: %#", [NSHTTPCookieStorage sharedHTTPCookieStorage].cookies);
// retrieve the doc from url
// block the call to wait for response for kMaxBlockingTimeHttpSeconds
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
NSURLSessionDownloadTask *getDocTask = [session downloadTaskWithURL:[NSURL URLWithString:request.url]
completionHandler:^(NSURL *location,
NSURLResponse *response,
NSError *error)
{
if (error) {
NSLog(#"Error retrieving document from %#, Error: %#",
request.url, error);
res.errorCode = SCPErrorDocumentGetError;
res.errorMessage = [error localizedDescription];
} else {
mimeType = response.MIMEType;
documentData = [NSData dataWithContentsOfURL:location];
}
dispatch_semaphore_signal(sema);
}];
[getDocTask resume];
dispatch_time_t timeout = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kMaxBlockingTimeHttpSeconds * NSEC_PER_SEC));
dispatch_semaphore_wait(sema, timeout);
if (!documentData) {
DLog(#"Response: %#", [res jsonDict]);
self.data = [NSJSONSerialization dataWithJSONObject:[res jsonDict] options:NSJSONWritingPrettyPrinted error:nil];
return;
}
NSString *str = [[NSString alloc] initWithData:documentData encoding:NSISOLatin1StringEncoding];
DLog(#"%#", str);
The NSLog printout of the cookie is,
"",
But this is not sent in the request header.
Adding the cookie header directly in the sessionConfig worked for me. But why did not the shareCookie work. This is supposed to work according the the documentation.
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfig.HTTPAdditionalHeaders = #{#"Cookie" : request.cookie};
Related
I am trying to proxy my requests in a NSURLConnection by using the code below, My problem is that I am getting a strange response from what seems to be the proxy when all I should be getting back is a IP address to show that the proxy is working. My NSURLResponse is fine so i am not sure what is really going on here. Any help much appreciated, Thanks!
NSString* proxyHost = #"http://180.177.**.***";
NSNumber* proxyPort = [NSNumber numberWithInt:80];
NSDictionary *proxyDict = #{
#"HTTPEnable" : [NSNumber numberWithInt:1],
(NSString *)kCFStreamPropertyHTTPProxyHost : proxyHost,
(NSString *)kCFStreamPropertyHTTPProxyPort : proxyPort,
(NSString *)kCFProxyTypeKey : (NSString *)kCFProxyTypeHTTP,
};
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
configuration.connectionProxyDictionary = proxyDict;
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://myexternalip.com/raw"]];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"%#",error);
NSLog(#"NSURLSession got the response [%#]", response);
NSLog(#"NSURLSession got the data [%#]", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];
\\ This is what I am getting back when i should just be getting back the proxy IP
<html><head><meta http-equiv="refresh" content="0;url=http://www.dnsrsearch.com/index.php? origURL=http://myexternalip.com/raw&bc="/></head><body><script type="text/javascript">window.location="http://www.dnsrsearch.com/index.p hp? origURL="+escape(window.location)+"&r="+escape(document.referrer)+"&bc="; </script></body></html>
///And this is my NSURLResponse///
{ URL: http://myexternalip.com/raw } { status code: 200, headers {
"Cache-Control" = "no-cache";
Connection = close;
"Content-Encoding" = gzip;
"Content-Type" = "text/html";
Date = "Fri, 12 Feb 2016 02:20:34 GMT";
Expires = "Fri, 12 Feb 2016 02:20:33 GMT";
Server = nginx;
"Transfer-Encoding" = Identity;
Vary = "Accept-Encoding";
} }
I have this NSURLSessionDataTask and I'm getting a Base64 string from the completionHandler. I'm having trouble converting it back into plaintext using the NS Encoding libraries even after looking up various posts.
Decode a Base64 string in objective-c ,
Base64 Decoding in iOS 7+ ,
Convert between UIImage and Base64 string
String from completionHandler^(Data) = InsnYWN0aW9uJzondGVzdCcsICdpbnB1dCc6J3Rlc3QnfSI=
Code used to try and decode:
NSString *baseString =[data base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength];
I was hoping someone could lead me in the right direction. Thanks.
Full Function - inspired by (http://hayageek.com/ios-nsurlsession-example/):
-(void) httpPostWithCustomDelegate
{
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
NSURL * url = [NSURL URLWithString:#"http://XXX.XXX.XXX.XXX"];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
NSData * params =[#"{'action':'test', 'input':'test'}" dataUsingEncoding:NSUTF8StringEncoding];
NSString * newParams = [params base64EncodedStringWithOptions:0];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[newParams dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//NSLog(#"Response:%# %#\n", response, error);
if(error == nil)
{
NSString *baseString =[data base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength];
//NSString *baseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Data = %#",baseString);
}
}];
[dataTask resume];
}
data contains the base64 encoded string (which represented data that represented some original object). So you need to convert data to the actual NSData representing whatever it was that was originally encoded.
Basically you need to reverse the original encoding steps.
If you are using iOS 7 or later you can do:
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//NSLog(#"Response:%# %#\n", response, error);
if (data) {
NSData *originalData = [[NSData alloc] initWithBase64EncodedData:data options:0];
// Do something with the decoded data
} else {
NSLog(#"error = %#", error);
}
}];
I used dispatch async to get som info from facebook , but i can't know when asyn finish
-(void)shareScoreViaFB:(int)score{
__block NSDictionary * dic;
ACAccountStore *_accStore=[[ACAccountStore alloc]init];
ACAccountType *_accType =[_accStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSDictionary *options = #{
ACFacebookAppIdKey:_mAppID,
ACFacebookPermissionsKey: #[#"publish_actions"],
ACFacebookAudienceKey: ACFacebookAudienceFriends
};
[_accStore requestAccessToAccountsWithType:_accType options:options completion:^(BOOL granted, NSError *e) {
if (granted) {
NSArray *accounts = [_accStore accountsWithAccountType:_accType];
_accFB = [accounts lastObject];
// [self openShareDialog];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
dic =[self getListScore];
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(#"data1: %#",dic);
});
});
};
}];
}
And method to get info
-(NSDictionary *)getListScore{
__block NSDictionary * dict=nil;
NSString *url =[NSString stringWithFormat:#"https://graph.facebook.com/%#/scores",_mAppID];
NSURL * strURL =[NSURL URLWithString:url];
NSDictionary * parameters =[NSDictionary dictionaryWithObjectsAndKeys:#"score,user",#"fields", nil];
SLRequest * request =[SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET URL:strURL parameters:parameters];
request.account = _accFB;
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if (!error && responseData) {
dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
NSLog(#"%#",dict[#"data"]);
// return dict[#"data"];
}
}];
return dict;
}
When i run' the log show:
- dict1: null.
- dict: OK (this show true value).
How i wait for dispatch_asyn finish and set this value to main interface?
Try doing it as follows:
-(void)shareScoreViaFB:(int)score{
__block NSDictionary * dic;
ACAccountStore *_accStore=[[ACAccountStore alloc]init];
ACAccountType *_accType =[_accStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSDictionary *options = #{
ACFacebookAppIdKey:_mAppID,
ACFacebookPermissionsKey: #[#"publish_actions"],
ACFacebookAudienceKey: ACFacebookAudienceFriends
};
[_accStore requestAccessToAccountsWithType:_accType options:options completion:^(BOOL granted, NSError *e) {
if (granted) {
NSArray *accounts = [_accStore accountsWithAccountType:_accType];
_accFB = [accounts lastObject];
NSString *url =[NSString stringWithFormat:#"https://graph.facebook.com/%#/scores",_mAppID];
NSURL * strURL =[NSURL URLWithString:url];
NSDictionary * parameters =[NSDictionary dictionaryWithObjectsAndKeys:#"score,user",#"fields", nil];
SLRequest * request =[SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET URL:strURL parameters:parameters];
request.account = _accFB;
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if (!error && responseData) {
dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
NSLog(#"%#",dict[#"data"]);
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(#"data1: %#",dic);
});
}
}];
};
}];
}
I am trying to to use mail api from sendgrid.com but everytime it finishes with failure block.
Also I don't understand how to send the image as an attachment in the email. Can anybody tell me whats wrong in below code & how can I send image ? I am using below code for now
-(void)sendEmail
{
NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
[params setValue:#"username" forKey:#"api_user"];
[params setValue:#"sdsfddf23423" forKey:#"api_key"];
[params setValue:#"test#gmail.com" forKey:#"to"];
[params setValue:#"test user" forKey:#"toname"];
[params setValue:#"Test SendGrid" forKey:#"subject"];
[params setValue:#"Test SendGrid from iOS app" forKey:#"text"];
[params setValue:#"noreply#gmail.com" forKey:#"from"];
NSURL *url = [NSURL URLWithString:#"https://sendgrid.com/api"];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL: url];
NSMutableURLRequest *request = [client requestWithMethod:POST path:#"/mail.send.json" parameters:params];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
DLog(#"Get latest product info response : %#", response);
NSLog(#"Success");
} failure: ^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure");
}];
[operation start];
}
Thanks in advance.
Update
I made some changes in code & now I can send the email successfully as below
-(void)sendEmailWithoutImage
{
NSDictionary *parameters = #{#"api_user": #"username",
#"api_key": #"sdsfddf23423",
#"subject":#"Test SendGrid",
#"from":#"noreply#gmail.com",
#"to":#"test#gmail.com",
#"text":#"Test SendGrid from iOS app"};
[[MyAPIClient sharedAPIClient] POST:#"mail.send.json" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject)
{
NSLog(#"Success::responseObject : %#", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error::Mail response : %#", error);
}];
}
But when I try to send the image as attachment then it result in 400 bad request. So I think there is some error in my file uploading block. Here is my code
-(void)sendEmailWithImage
{
NSDictionary *parameters = #{#"api_user": #"username",
#"api_key": #"sdsfddf23423",
#"subject":#"Test SendGrid",
#"from":#"noreply#gmail.com",
#"to":#"test#gmail.com",
#"text":#"Test SendGrid from iOS app"};
[[MyAPIClient sharedAPIClient] POST:#"mail.send.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
UIImage *image = [UIImage imageNamed:#"redWine.png"];
NSData *imageToUpload = UIImagePNGRepresentation(image);
[formData appendPartWithFileData:imageToUpload name:#"files" fileName:[NSString stringWithFormat:#"%#",#"abc.png"] mimeType:#"image/png"];
}
success:^(NSURLSessionDataTask *task, id responseObject)
{
NSLog(#"Success::responseObject : %#", responseObject);
}
failure:^(NSURLSessionDataTask *task, NSError *error)
{
NSLog(#"Error::Mail response : %#", error);
}];
}
Can you anybody tell me whats going wrong while uploading the image ?
Thanks
Just modified your code a little. It looks like there was an issue with the parameters being sent and the URL path.
Also since you are already using AFNetworking to make your POST request, you can follow their docs and example on how to send a photo over here: http://cocoadocs.org/docsets/AFNetworking/2.0.1/
NSDictionary *parameters = #{#"api_user": #"username",
#"api_key": #"sdsfddf23423",
#"Test SendGrid":#"test",
#"from":#"noreply#gmail.com",
#"to":#"test#gmail.com",
#"text":#"Test SendGrid from iOS app"};
NSURL *url = [NSURL URLWithString:#"https://sendgrid.com/api/"];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL: url];
NSMutableURLRequest *request = [client requestWithMethod:#"POST" path:#"mail.send.json" parameters:parameters];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
// DLog(#"Get latest product info response : %#", response);
NSLog(#"Success: %#", response);
} failure: ^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#",error);
}];
[operation start];
Update**
Created a Sendgrid-ios library to make it easier to send an email and photo attachment.
//create Email Object
gridmail *msg = [gridmail user:#"username" andPass:#"password"];
//set parameters
msg.to = #"foo#bar.com";
msg.subject = #"subject goes here";
msg.from = #"me#bar.com";
msg.text = #"hello world";
msg.html = #"<h1>hello world!</h1>";
//Image attachment
[msg attachImage:self.photo];
//Send email through Web API Transport
[msg sendWithWeb];
In my current xcode project, I need to send parameter values to a url and need to retrieve an xml file based on the parameter values sent.
I tried the below code but it's not working:
(IBAction)myButtonClick:(id)sender
{
NSURL *oRequestURL =
[NSURL URLWithString:#"http://xyz .com/air/1.0/search?from=MAA&to=CJB&depart-date=2012-06-30&adults=2&children=2&infants=1&way=one&cabin-type=Economy&sort=asc"];
NSMutableURLRequest *oRequest = [[[NSMutableURLRequest alloc]init]autorelease];
[oRequest setHTTPMethod:#"POST"];
[oRequest setURL: oRequestURL];
NSMutableData *oHttpBody = [NSMutableData data];
[oHttpBody appendData:[#"This is HTTP Request body" dataUsingEncoding:NSUTF8StringEncoding]];
[oRequest setValue:[oHttpBody length] forHTTPHeaderField:#"Content-Length"];
NSError *oError = [[NSError alloc]init];
NSHTTPURLResponse *oResponseCode = nil;
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:oRequest returningResponse:oResponseCode error:oError];
if ([oResponseCode statusCode]> 200) {
NSLog(#"Status code is greater than 200");
}
NSString *strResult=[[NSString alloc]initWithData:oResponseData encoding:NSUTF8StringEncoding];
NSLog(#"The result is %s",strResult);
}
I have searched many sites and books but could not find a solution.
Would be of great help if a link to a tutorial or some other useful resource can be provided. Appreciate your great help.
Thank You.
Hi,
I have found the solution. The code is as below. Hope it helps someone else:)
- (IBAction)myButtonPressed:(id)sender
{
NSString *urlAsString = #"http://api.abc.com/air/1.0/search?from=MAA&to=CJB&depart-date=2012-09-30&adults=2&children=2&infants=1&way=one&cabin-type=Economy&sort=asc";
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setValue:#"2193141de2g7e2a34bb19bc3aa52b3b5" forHTTPHeaderField:#"X-XX-API-KEY"];
[urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:#"GET"];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection
sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length]>0 &&
error == nil)
{
NSString *html = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"HTML = %#", html);
}
else if ([data length]== 0 && error==nil) {
NSLog(#"Nothing was downloaded");
}
else if (error!= nil) {
NSLog(#"Error occured = %#", error);
}
}];
}