I have an AWS EC2 instance and an app that I created. The app is for people who get migraines (tracks info, tells them what their trigger(s) are). Now I want to be able to send user input from my application to a server so that I can see trends. I am having difficulty connecting to the server and finding out how I would be able to write files to the server.
I have written this method:
- (void) sendDataToServer:(NSString *)url :(NSString *)key : (NSString *) content{
// define your form fields here:
//NSString *content = #"field1=42&field2=Hello";
NSString *address = [NSString stringWithFormat:#"ssh -i %# %#", key, url];
NSLog(#"%#", address);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:address]];
[request setHTTPMethod:#"POST"];
NSData *contentData = [content dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:contentData];
NSString *postLength = [NSString stringWithFormat:#"%d",[contentData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// generates an autoreleased NSURLConnection
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn){
NSLog(#"connection");
}
//[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
//[self doSomethingWithData:data];
if (error){
NSLog(#"ERROR");
}
}];
}
I put the private key from my key pair into the app. How would I use that to connect? Should I not be using my private key? Should I be doing this differently?
Should I be doing this differently?
Absolutely, 100%, YES. You don't want to let people SSH into your server, especially by embedding your private key into an app binary. It's crazy easy for someone to get it, then wreak havoc upon your server.
Don't do this.
Instead, I would get a web server like Apache running on your instance (it's trivial), and write an application (in PHP, Rails (with Passenger), Python, whatever) that saves files to the server's hard drive. You'll also want to get an Elastic IP address so that it stays constant, as ashack mentioned.
In your iOS app, you'll want to send a POST request to your server. See Sending an HTTP POST request on iOS, it's essentially what you're doing now.
Don't publish your private SSH key. It's private for a good reason.
Related
I am trying to set up an iOS client to use SignalR-ObjC with our web service. When we use the long polling approach, everything seems to work but it has issues of its own with our production environment. So I have been instructed to switch to using the Web Sockets approach. Based on code examples I've seen online I think it should be working with what I have but the service is returning an error through the webSocket:didFailWithError: method. Here's the error:
Error Domain=org.lolrus.SocketRocket Code=2132 "received bad response code from server 403" UserInfo={NSLocalizedDescription=received bad response code from server 403}
Here's my code for setting up the connection, found in our AppDelegate file:
<!-- language:objective c -->
-(void)initializePushNotificationsConnection
{
// Connect to the hub on the service
SRHubConnection* localHubConnection = [SRHubConnection connectionWithURL:kSignalRServiceUrl];
SRHubProxy* notifications = (SRHubProxy*)[localHubConnection createHubProxy:#"notificationHub"];
[notifications on:#"notificationSent" perform:self selector:#selector(addMessage:)];
localHubConnection.started = ^{
NSString* userGuid = [OURAppSettings sharedSettings].loginModel.theUser.userGuid;
if (!userGuid)
userGuid = #"";
NSString* connId = self.hubConnection.connectionId;
if (!connId)
connId = #"";
NSDictionary* connectionDict = #{#"UserGuid": userGuid, #"Model": connId};
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:connectionDict options:0 error:nil];
NSURL* connectionRegistrationServiceUrl = [NSURL URLWithString:kSignalRConnectionRegistrationUrl];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:connectionRegistrationServiceUrl];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse* response, NSData* data, NSError* connectionError)
{
if (connectionError)
{
NSLog(#"Error: %#", connectionError);
return;
}
}];
return;
};
//Set the object to the local property to break the strong connection so the block can reference the object
self.hubConnection = localHubConnection;
SRWebSocketTransport *webSocket = [[SRWebSocketTransport alloc] init];
[self.hubConnection start:webSocket];
}
I've tried multiple suggestions from Github and SO but none of them are solving this issue. I suspect there is a problem with how the web service is setup but I'm not an IIS expert nor do I have easy access to the setup. I'm basically just guessing at solutions at this point, so if anyone has any thoughts or suggestions at all I'm open to hearing them.
I need some help with a LoginViewController.
Basically I have a small app, and I need to post some data to the app and Im new to POST and JSON. If I can get some help and understanding that would be highly appreciated. Below are some requirements im working with. My .m file is labled as LoginViewController. This is what I have so far
-(void)setRequest {
#pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// A response has been received, this is where we initialize the instance var you created
// so that we can append data to it in the didReceiveData method
// Furthermore, this method is called each time there is a redirect so reinitializing it
// also serves to clear it
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
[_responseData appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse*)cachedResponse {
// Return nil to indicate not necessary to store a cached response for this connection
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// The request has failed for some reason!
// Check the error var
}
-(void)PostRequest{
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://dev.apppartner.com/AppPartnerProgrammerTest/scripts/login.php"]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
// This is how we set header fields
[request setValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSString *stringData = #"some data";
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
}
I dont know if I'm even setting this up right. I saw many hTTP posts and what not, but im still confused on how I write this syntax and do I need to add anything additional.
I need to:
Send an asynchronous POST request to "some url"
The POST request must contain the parameters 'username' and 'password'
Will receive a JSON response back with a 'code' and a 'message'
Display the parsed code and message in a UIAlert along with how long the api call took in miliseconds
The only valid login is username: Super password: qwerty
When a login is successful, tapping 'OK' on the UIAlert should bring us back to the MainMenuViewController
I'm assuming the methods inside methods are a typo.
Unless you have a particular reason to implement all those delegate methods, you're probably better off using either
NSURLSessionDataTask *task =
[[NSURLSession sharedSession] dataTaskWithRequest:request
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
// Code to run when the response completes...
}];
[task resume];
or the equivalent using NSURLConnection's sendAsynchronousRequest:queue:completionHandler: method if you still need to support iOS 6 and earlier and/or OS X v10.8 and earlier.
But the big thing you're missing is the encoding of the request body. To do that, you'll probably want to use URL encoding and specify the appropriate MIME type for that as shown here:
https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/WorkingwithURLEncoding/WorkingwithURLEncoding.html
Basically, you construct a string by string concatenation in the form "user=ENCODEDUSERNAME&pass=ENCODEDPASSWORD" where the two encoded values are constructed like this:
NSString *encodedString = (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(
kCFAllocatorDefault,
(__bridge NSString *)originalString,
NULL,
CFSTR(":/?#[]#!$&'()*+,;="),
kCFStringEncodingUTF8);
Do not be tempted to use stringByAddingPercentEscapesUsingEncoding: and friends. They will do the wrong thing if your strings contain certain reserved URL characters.
I would suggest that you try working with AFNetworking Library.
You can find the code here.
And a very good tutorial here.
You can do like that for this.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request addValue:#"YourUsername" forHTTPHeaderField:#"Username"];
[request addValue:#"YourPassword" forHTTPHeaderField:#"Password"];
[NSURLConnection
sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// TODO: Handle/Manage your response ,Data & errors
}];
-(IBAction)registerclick:(id)sender
{
if (_password.text==_repassword.text)
{
[_errorlbl setHidden:YES];
NSString *requstUrl=[NSString stringWithFormat:#"http://irtech.com/fresery/index.php?route=api/fresery/registerCustomer"];
NSString *postString=[NSString stringWithFormat:#"name=asd&email=sooraj&phonenumber=8111&password=soorajsnr&type=1&facebookid=&image_path="];
// _name.text,_email.text,_mobile.text,_password.text
NSData *returnData=[[NSData alloc]init];
NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:requstUrl]];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[postString length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
resp=[NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];
c=[[resp valueForKey:#"status" ]objectAtIndex:0];
b=[[resp valueForKey:#"message"]objectAtIndex:0];
I want to like and comment in my iOS application.But the problem is whenever I call my API the response comes in the form of this `error:message:(#200)'. App does not have permission to make this call and sometimes it will give input parameter is required.The permissions i give are 'basic_info','email','user_likes' and 'read_stream'. I am passing object id and access token in my like and comment API.
Like API code:
NSString *theWholeUrl = [NSString stringWithFormat:#"https://graph.facebook.com/%#/likes?access_token=%#",self.friendId,[FBSession activeSession].accessTokenData.accessToken];
NSLog(#"Value of theWholeUrl%#",theWholeUrl);
NSURL *facebookUrl = [NSURL URLWithString:theWholeUrl];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:facebookUrl];
[req setHTTPMethod:#"POST"];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&err];
NSString *content = [NSString stringWithUTF8String:[responseData bytes]];
You need the publish_actions permission to be able to like and comment on content programmatically via the API.
I have an iOS app that has a series of images in a scrollview (camera pictures). I want to be able to post these on to a url individually or collectively as a group.
Can someone point me to an example or some sample code that would get me started?
Much appreciated
in that case if you if you set up your server (how do this i don`t now, because i used quickblox - ready-made solution) try send GET-request to the server. You can try this like this:
(source - How to send a Get request in iOS? )
NSString *getString = [NSString stringWithFormat:#"parameter=%#",yourvalue];
NSData *getData = [getString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getLength = [NSString stringWithFormat:#"%d", [getData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"https:yoururl"]];
[request setHTTPMethod:#"GET"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:getData];
self.urlConnection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
NSAssert(self.urlConnection != nil, #"Failure to create URL connection.");
// show in the status bar that network activity is starting
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
For more advanced preferences I would advise you try learn http://allseeing-i.com/ASIHTTPRequest/
For this you can create file server or use other maded. Look this: http://quickblox.com/ - they has blobs and ios api for their server, so download|upload files simple implemented in code.
First, you need register your account and then register your app.( https://admin.quickblox.com/signin ) (it's not difficult, few minuts)
Then, using instructions from site added Quickblox auth to your app and then use QBBlobs for dowload photo. Good luck!
everyone! My english is poor and sorry fot that.
I want implement a function in my test iOS application.
There is a .NET Webservice API just like
"https://xxx.xxx.xx.xxx/FMS/Pages/Service/FMService.svc/Login"
I want to connect the API with two parameters:user and pass
using the GET method,and the url will be like:
"https://xxx.xxx.xx.xxx/FMS/Pages/Service/FMService.svc/Login?user=xxx&pass=xxx"
if login, the Webservice will return a JSON value just like {"d":"success"}
if not, it will also return a JSON value like {"d":"failure"}
I am using the ASIHTTPRequest framework and JSON framework
I dont know how to implement the function. So please help me, thanks a lot.
Best wishes!
NSURL *url = [NSURL URLWithString:#"https://192.168.1.245/FMS/Pages/Service/FMService.svc/Login?user=jiangxd&pass=123456"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addRequestHeader:#"Accept" value:#"application/json"];
[request addRequestHeader:#"Content-Type" value:#"application/json"];
[request setRequestMethod:#"GET"];
[request setDelegate:self];
[request startAsynchronous];
NSString *responseString = [request responseString];
NSDictionary *responseDict = [responseString JSONValue];
NSString *unlockCode = [responseDict objectForKey:#"d"];
NSLog(#"%#",unlockCode);
The unlockCode is always null... and I dont understand why!
NSURL *url = [NSURL URLWithString:#"https://192.168.1.245/FMS/Pages/Service/FMService.svc/Login?user=jiangxd&pass=123456"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
NSError *error = [request error];
if (!error)
{
NSString *responseString = [request responseString];
NSDictionary *responseDict = [responseString JSONValue];
NSString *unlockCode = [responseDict objectForKey:#"d"];
NSLog(#"%#",unlockCode);
}
else
{
NSLog(#"%#",[error description]);
}
And now I change startAsynchronous to startSynchronous but there is also an error:
Error Domain=ASIHTTPRequestErrorDomain Code=1 "A connection failure occurred: SSL problem (Possible causes may include a bad/expired/self-signed certificate, clock set to wrong date)" UserInfo=0x6b81640 {NSUnderlyingError=0x6b811b0 "The operation couldn’t be completed. (OSStatus error -9807.)", NSLocalizedDescription=A connection failure occurred: SSL problem (Possible causes may include a bad/expired/self-signed certificate, clock set to wrong date)}
NOTICE:The url is https, not http!(Is this the reason that I get an error?)
But if I access the url directly with browser, the Webservice will return the right value...
Thank you!
You should probably try it, and then post your code. You're asking someone to write this entire function for you, and I don't think that that is the purpose of this site.
Secondly, the developer behind the ASIHTTPRequest is no longer supporting it. Unless the community picks up, you might want to just learn how to do NSURLConnections from scratch.
Edit: There we go. So, you're doing this asynchronosly which means that when you start it, you're not immediately going to have the response. Have you setup your callbacks to process the response?
- (void)requestFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
// Use when fetching binary data
NSData *responseData = [request responseData];
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error];
}