POST Request with AFNetworkings AFHTTPSessionManager gets interpreted as GET on Heroku - heroku

I am currently trying to POST to my heroku server.
Everything works fine locally but if i change my url for the AFHttpSessionmanager to the heroku App, my App wont work anymore cause the post requests gets interpreted as a GET Request on the Heroku-Side ..
This is how i do the Post-request :
NSString * postPath = [NSString stringWithFormat:#"/freetextquestions/%ld/freetextanswers.json",(long)identifier];
[[AskMeClient sharedClient] POST:postPath parameters: [NSDictionary dictionaryWithObject:self.answerTextField.text forKey:#"text"]
success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"%#", responseObject);
[self dismissViewControllerAnimated:YES completion:nil];
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"%#", error);
UIAlertView * alert = [[UIAlertView alloc]initWithTitle:#"Ooops ..." message:error.localizedDescription delegate:nil cancelButtonTitle:#"dismiss" otherButtonTitles: nil];
[alert show];
}];
This is my Client :
#implementation AskMeClient
+(instancetype)sharedClient {
static AskMeClient *_sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedClient = [[AskMeClient alloc] initWithBaseURL:[NSURL URLWithString:AskMeAPIBaseURLString]];
_sharedClient.securityPolicy = [AFSecurityPolicy defaultPolicy];
_sharedClient.responseSerializer = [AFJSONResponseSerializer serializer];
_sharedClient.requestSerializer = [AFJSONRequestSerializer serializer];
[_sharedClient.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
});
return _sharedClient;
}
#end
and this is what heroku says :
2014-02-24T00:32:35.246169+00:00 heroku[router]: at=info method=GET path=/freetextquestions/3/freetextanswers host=topsecretapp.herokuapp.com request_id=b2876fdb-d4bf-403a-a05a-4539830f9f0e fwd="193.175.119.11" dyno=web.1 connect=9ms service=44ms status=404 bytes=351
I tried everything to eliminate this error but i cant get it to work ..
Does anybody has an idea what i am doing wrong ? Or is this a Heroku-Error ?

I found a Solution for this.
If i use the subdomain provided by heroku it seems that the HTTP-Method gets lost in some way, maybe caused by some forwardings or redirects.
Now i am using a other domain that references on to my heroku-App and everything works fine.

Related

XPC Between two cocoa applications in workspace, the NSXPCConnection is immediately being invalidated

I have two Cocoa Applications, one is going to be the sender and another the receiver in this XPC relationship.
In the applicationDidFinishLaunching in the sender, I first open the second receiver application
NSError* error = nil;
NSURL* url = [[NSBundle mainBundle] bundleURL];
url = [url URLByAppendingPathComponent:#"Contents" isDirectory:YES];
url = [url URLByAppendingPathComponent:#"MacOS" isDirectory:YES];
url = [url URLByAppendingPathComponent:#"TestXPCHelper.app" isDirectory:YES];
[[NSWorkspace sharedWorkspace] launchApplicationAtURL:url
options:NSWorkspaceLaunchWithoutActivation
configuration:[NSDictionary dictionary]
error:&error];
if ( error )
{
NSLog(#"launchApplicationAtURL:%# error = %#", url, error);
[[NSAlert alertWithError:error] runModal];
}
Then I create my NSXPCConnection
assert([NSThread isMainThread]);
if (self.testConnection == nil) {
self.testConnection = [[NSXPCConnection alloc] initWithMachServiceName:NEVER_TRANSLATE(#"com.TechSmith.TestXPCHelper") options:NSXPCConnectionPrivileged];
self.testConnection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:#protocol(TestXPCProtocol)];
self.testConnection.interruptionHandler = ^{
NSLog(#"Connection Terminated");
};
self.testConnection.invalidationHandler = ^{
self.testConnection.invalidationHandler = nil;
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.testConnection = nil;
}];
};
[self.testConnection resume];
}
Then I try to send a message over the connection (the connection is already invalidated by here)
id<TestXPCProtocol> testRemoteObject= [self.testConnection remoteObjectProxy];
[testRemoteObject testXPCMethod2];
[[self.testConnection remoteObjectProxyWithErrorHandler:^(NSError * proxyError){
NSLog(#"%#", proxyError);
}] testXPCMethod:^(NSString* reply) {
NSLog(#"%#", reply);
}];
And here is the app delegate for my receiver application:
#interface AppDelegate () <NSXPCListenerDelegate, TestXPCProtocol>
#property (weak) IBOutlet NSWindow *window;
#property NSXPCListener *xpcListener;
#end
#implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
NSLog(#"TESTING123");
self.xpcListener = [[NSXPCListener alloc] initWithMachServiceName:#"com.TechSmith.TestXPCHelper"];
self.xpcListener.delegate = self;
[self.xpcListener resume];
}
- (void)applicationDidBecomeActive:(NSNotification *)notification {
NSLog(#"ACTIVE234");
}
- (void)applicationWillTerminate:(NSNotification *)aNotification {
// Insert code here to tear down your application
}
- (void)run
{
NSLog(#"RUNNING");
// Tell the XPC listener to start processing requests.
[self.xpcListener resume];
// Run the run loop forever.
[[NSRunLoop currentRunLoop] run];
}
- (BOOL)listener:(NSXPCListener *)listener shouldAcceptNewConnection:(NSXPCConnection *)newConnection
{
NSLog(#"LISTENING");
assert(listener == self.xpcListener);
#pragma unused(listener)
assert(newConnection != nil);
newConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:#protocol(TestXPCProtocol)];
newConnection.exportedObject = self;
[newConnection resume];
return YES;
}
- (void)testXPCMethod:(void(^)(NSString * version))reply
{
NSLog(#"HEY");
reply(#"REPLY HERE");
}
- (void)testXPCMethod2
{
NSLog(#"TWO!");
}
Here is the proxyError when I try to send a message over the connection:
Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service
named com.TechSmith.TestXPCHelper was invalidated." UserInfo={NSDebugDescription=The
connection to service named com.TechSmith.TestXPCHelper was invalidated.}
So I think I am doing something wrong with my instantiation of the NSXPCConnection. I can't find a good example of two applications speaking to eachother-- it's always one application and a service. Is that what my problem is? I need a service inbetween the applications talking?
Is there any way to get more information on why this connection is being invalidated? That would also help a lot
So pretty straight forward problem here,
Turns out initWithMachServiceName is explicitly looking for a mach service. I was using an identifier of another application process.
If I actually use an identifier of a valid mach service, there is no issue
Note that there are two other ways to create an NSXPCConnection,
with an NSXPCEndpoint or with a XPCService identifier

IOS STHTTPRequest going into Error Block

I a using STHTTPRequest to fetch JSON data in an IOS App. Please see the code below.
When i am testing on Iphone 6 IOS8.0, Sometimes the code is going into error block. Its not happening always , only sometimes. Could anyone help ? Thank u
if(showActivity)
{
[self ShowActivityIndicatorWithTitle:#"Loading..."];
}
STHTTPRequest *request1 = [STHTTPRequest requestWithURLString:[NSString stringWithFormat:#"%#%#",kBaseUrl,api]];
[request1 setTimeoutSeconds:120.0f];
[request1 setHeaderWithName:#"Content-Type" value:#"application/x-www-form-urlencoded"];
[request1 setHTTPMethod:#"POST"];
request1.rawPOSTData = [postData dataUsingEncoding:NSUTF8StringEncoding];
request1.completionDataBlock = ^(NSDictionary *headers, NSData* data)
{
[self HideActivityIndicator];
if(handler != nil)
{
NSError* connectionError;
handler(JSONObjectFromData(data),connectionError);
}
};
request1.errorBlock=^(NSError *error)
{
NSLog(#"Error: %#", [error localizedDescription]);
if(error != nil)
{
[[[UIAlertView alloc] initWithTitle:#"Connection Error !" message:kAlertInternetConnection delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil] show];
[self HideActivityIndicator];
}
};
[request1 startAsynchronous];
I think i found the solution. Basically IOS takes the "Keep Alive" Parameter from first response, and thinks the connection is persistent. When the next JSON call is made, IOS is trying to use existing connection, which is expired. I have added header('Connection: close'); in each PHP web service. I am telling ios in each web service that the connection is closed. I am not sure if it is good way to do it. I have tested for 20 min on device. Its working. I appreciate any thoughts on this.
In PHP I added:
ob_end_clean();
header("Connection: close");
ignore_user_abort(true); // just to be safe
header('Content-Type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Content-Length: ' . filesize($file));
readfile($file);
And it worked!

Unsupported URL on ios 8

I'm trying to fetch a json from google places with the following code:
NSString *query = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=%i&types=%#&sensor=true&key=%#", center.latitude, center.longitude, rad, types, kGOOGLE_API_KEY];
NSLog(#"%#",query);
NSURL *googleRequestURL=[NSURL URLWithString:query];
[NSURLConnection sendAsynchronousRequest:[[NSURLRequest alloc] initWithURL:googleRequestURL] queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(#"Error fetching data: %#",[error description]);
} else {
//To-do
}
}];
The resulting url is: https://maps.googleapis.com/maps/api/place/search/json?location=37.337566,-122.041202&radius=1000&types=accounting|bowling_alley|doctor&sensor=true&key=MY_KEY
(my key is ommitted for obsious reasons)
Which works fine from my laptop's browser, but return the error:
Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo=0x7fe47bc138f0 {NSLocalizedDescription=unsupported URL, NSUnderlyingError=0x7fe47be9dbe0 "unsupported URL"}
I tried using http instead of https (in the browser it returns a json with some error message, but still returns something) with no success.
What am I doing wrong?
This is how I got it resolved. Good Luck!
NSString *google = #"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=%f,%f&radius=500&types=%#&key=%#";
NSString *link = [NSString stringWithFormat:google, coordinate.latitude, coordinate.longitude, types, GOOGLE_KEY];
NSURL *url = [NSURL URLWithString:[link stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];

Send email from iOS app using SendGrid

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];

Xcode 'autorelease is unavailable in URL request

I have the following code in my .m file:
- (IBAction)LoginButton:(id)sender {
// create string contains url address for php file, the file name is phpFile.php, it receives parameter :name
NSString *strURL = [NSString stringWithFormat:#"http://www.myURL.com/verify.php?Email=%#",Email.text];
// to execute php code
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
// to receive the returend value
NSString *strResult = [[[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding]autorelease];
NSLog(#"%#", strResult);
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Result:"
message:strResult
delegate:nil
cancelButtonTitle:#"Okay"
otherButtonTitles:nil];
[alert show];
}
And I am getting that autorelease is unavailable in automatic reference counting mode.
It seems to be an issue with the following line:
NSString *strResult = [[[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding]autorelease];
How can I solve this?
Just delete the autorelease call; if you are using ARC (Automatic Reference Counting) you don't need to worry about memory management.

Resources