sending the device token and app version to server [duplicate] - iphone

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
How to send the device token and app version to server
I have implemented the push notification service in my application, But am not able to send the device token id and app version to server.
Thanks in advance.
Here is the my code
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
// Get Bundle Info for Remote Registration (handy if you have more than one app)
NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:#"CFBundleVersion"];
// Prepare the Device Token for Registration (remove spaces and < >)
NSString *deviceToken = [[[[devToken description]
stringByReplacingOccurrencesOfString:#"<"withString:#""]
stringByReplacingOccurrencesOfString:#">" withString:#""]
stringByReplacingOccurrencesOfString: #" " withString: #""];
NSMutableString *urlString = [[BASE_URL mutableCopy] autorelease];
[urlString appendFormat:#"traceDeviceTokenId?tokenid=%#&version=%#",deviceToken, appVersion];
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *postLength = [NSString stringWithFormat:#"%d", [urlString length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"text/xml; charset=utf-16" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[urlString dataUsingEncoding:NSUTF16StringEncoding]];
NSLog(#"Request xml>>>>>> %#", urlString);
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseXml = [[NSString alloc] initWithData:urlData encoding:NSUTF16StringEncoding];
NSLog(#"Response xml>>>>>> = %#", responseXml);
}

You are obviously not sending anything back to the server in the code you provided. To send it to a server you can use SOAP. And to check if the token is the right format, write
NSLog(#"%#",deviceToken)

Related

Get http response code in ios when using sendSynchronousRequest [duplicate]

This question already has answers here:
how do I check an http request response status code from iOS?
(2 answers)
Closed 9 years ago.
I have a working http GET without using any third party bits, I am new to iOS so this was a struggle to setup initially. My code looks like:
-(NSString *) SendGetRequestToRest:(NSString *)urlEndString
{
NSString *userName = #"userN";
NSString *password = #"PassW";
NSString *urlBaseString = #"http://someurl.co.uk/";
NSString *urlString = [NSString stringWithFormat:#"%#%#", urlBaseString, urlEndString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
NSString *str1 = [NSString stringWithFormat:#"%#:%#", userName, password];
NSString *encodedString = [self stringByBase64EncodingWithString:str1];
[request addValue:[NSString stringWithFormat:#"Basic %#",encodedString] forHTTPHeaderField:#"Authorization"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *str = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"str: %#", str);
return str;
}
What I need to do is track when the status code of the http GET is not a nice 200, I saw How to check status of web server in iOS? and this looks promising i.e. add this:
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response
{
if ([response statusCode] == 404)
{
/// do some stuff
}
}
But I cant see how to connect this up to
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
as it doesnt accept a delegate?
You can use returningResponse parameter to get "response":
NSHTTPURLResponse *response = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
if ([response statusCode] == 404)
{
// Do whatever you want to do after getting response
}

Pass username and password in URL for authentication

I want ot pass username and password in URL(web service) for user authentication which will return true and false.I'm doing this as following:
NSString *userName = [NSString stringWithFormat:#"parameterUser=%#",txtUserName];
NSString *passWord = [NSString stringWithFormat:#"parameterPass=%#",txtPassword];
NSData *getUserData = [userName dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getUserLength = [NSString stringWithFormat:#"%d",[getUserData length]];
NSData *getPassData = [passWord dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getPassLength = [NSString stringWithFormat:#"%d",[getPassData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:#"http://URL/service1.asmx"]];
[request setHTTPMethod:#"GET"];
Now, I wanted to know How can I pass my username and password in this URL to make request.
Could any one please suggest or give some sample code?
Thanks.
Try this :-
NSString *userName = [NSString stringWithFormat:#"parameterUser=%#",txtUserName.text];
NSString *passWord = [NSString stringWithFormat:#"parameterPass=%#",txtPassword.text];
NSData *getUserData = [userName dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getUserLength = [NSString stringWithFormat:#"%d",[getUserData length]];
NSData *getPassData = [passWord dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getPassLength = [NSString stringWithFormat:#"%d",[getPassData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://URL/service1.asmx?%#&%#",userName,passWord]]];
[request setHTTPMethod:#"GET"];
Hope it helps you..
NSString *urlStr = [NSString stringWithFormat:#"http://URL/service1.asmx?%#&%#",userName,passWord];
[request setURL:[NSURL URLWithString:urlStr]];
To improve the secure , you may use the Http Basic Authentication.
There are answer here.
First off I would not pass a username and password across in a url. You should do this using post.
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://URL/service1.asmx?"]];
NSString *userName = [NSString stringWithFormat:#"parameterUser=%#",txtUserName];
NSString *passWord = [NSString stringWithFormat:#"parameterPass=%#",txtPassword];
NSString *postString = [NSString stringWithFormat:#"username=%#&password=%#",userName, passWord];
NSData *postData = [NSData dataWithBytes: [postString UTF8String] length: [postString length]];
//URL Requst Object
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:TIMEOUT];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: postData];
This is more secure then passing sensitive data across in a url.
Edit
To get the response you can check this out. NSURLConnection and AppleDoc NSURLConnection
You can use a few different methods to handle the response from the server.
You can use NSURLConnectionDelegate
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[self.connection start];
along with the delegate call backs:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"didReceiveData");
if (!self.receivedData){
self.receivedData = [NSMutableData data];
}
[self.receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"connectionDidFinishLoading");
NSString *receivedString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"receivedString:%#",receivedString);
}
Or you can also use NSURLConnection sendAsynchronousRequest block
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSString *receivedString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"receivedString:%#",receivedString);
}];

iPhone [request setTimeoutInterval:10] not working, app freezes

When I chnage to port number I'm connecting to to test the timout, my app freezes.
I am calling [request setTimeoutInterval:10];, which I assume should be 10 seconds. But, the app hangs. Could it have something to do with it being a local server?
Code:
// call this when program first starts
-(void) nSendMessage : (NSString *) name Password: (NSString *) password page: (NSString *) page
{
// set the url
NSString *address = #"http://localhost:1075/update";
address=[ address stringByAppendingString: page];
NSMutableURLRequest *request =
[[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:address]];
// post or get
[request setHTTPMethod:#"POST"];
// data to send
NSString *postString = #"username=iusername&password=ipassword";
NSString *sendString=[postString stringByReplacingOccurrencesOfString:#"iusername" withString: name];
sendString=[sendString stringByReplacingOccurrencesOfString:#"ipassword" withString: password];
[request setValue:[NSString
stringWithFormat:#"%d", [sendString length]]
forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[sendString
dataUsingEncoding:NSUTF8StringEncoding]];
[request setTimeoutInterval:10];
[[NSURLConnection alloc]
initWithRequest:request delegate:self];
//
//THE PROGRAM FREEZES HERE
//
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *response = [[NSString alloc] initWithData:urlData encoding:NSASCIIStringEncoding];
// Phrase repl
[self nUpdateDisplay:response];
}
Your question looks like a dupe of this one:
iPhone SDK: URL request not timing out
So to summarise: the timeout lower limit is at least four minutes, even if you pass in a smaller value.
And as detailed at the above link, using the asynchronous method is usually the best option. If you use synchronous, as you are doing above, and you're in the main runloop, you will block your UI completely, which will cause the 'hang' effect.

My app logs in twice with a URLRequest

When i press login in my app, it logs in twice in API instead of just once.., there is something wrong with this but i cant find what, because it just execute this code once.
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
NSHTTPURLResponse * response;
NSError * error;
NSMutableURLRequest * request;
NSString * params;
NSString *urlAddress = [NSString stringWithFormat:#"%#/?action=request&api=json&module=ManagementModule&function=startSession&instance=0",[ConnectServer returnserverip]];
NSLog(#"UPX %#",[ConnectServer returnserverip]);
NSLog(#"IP %#",[ConnectServer returnclientip]);
if([defaults boolForKey:#"enablePincode"]){
NSString *account = [defaults stringForKey:#"myAccount"];
NSString *username =[defaults stringForKey:#"myUsername"];
NSString *password = [defaults stringForKey:#"myPassword"];
NSString *clientip = [ConnectServer returnclientip];
NSString *clientname = [ConnectServer returnclientname];
params = [[[NSString alloc] initWithFormat:#"params=&auth[password]=%#&auth[mode]=%#&auth[account]=%#&auth[user]=%#&auth[rights]=%#&auth[user_ip]=%#&auth[client_name]=%#",password,#"password",account,username,#"user",clientip,clientname] autorelease];
}
else {
NSString *clientip = [ConnectServer returnclientip];
NSString *clientname = [ConnectServer returnclientname];
params = [[[NSString alloc] initWithFormat:#"params=&auth[password]=%#&auth[mode]=%#&auth[account]=%#&auth[user]=%#&auth[rights]=%#&auth[user_ip]=%#&auth[client_name]=%#",[myPassword text],#"password",[myAccount text],[myUsername text],#"user",clientip,clientname] autorelease];
}
request = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlAddress] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60] autorelease];
NSData *myRequestData = [params dataUsingEncoding:NSUTF8StringEncoding];
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[[NSURL URLWithString: urlAddress] host]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:myRequestData];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [myRequestData length]] forHTTPHeaderField:#"Content-Length"];
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"RESPONSE HEADERS: \n%#", [response allHeaderFields]);
request.URL = [NSURL URLWithString:urlAddress];
error = nil;
response = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"The server saw:\n%#", [[[NSString alloc] initWithData:data encoding: NSASCIIStringEncoding] autorelease]);
NSLog(#"Parameters: %#", params);
NSLog(#"Actual sended parameters to the server: %#", myRequestData);
NSString *Sresponse;
Sresponse = [[[NSString alloc] initWithData:data encoding: NSASCIIStringEncoding] autorelease];
There are two requests in the code:
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
and five lines down
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
Hint: In cases like this use wireshark or my favorite Charles which will decode SSL connections.
I guess it is possible. I mean, I am running APEX at this very moment and I have the same app. running in 3 different windows under the same user without having to log on. The only time I have to log on is when I change user.
So yes, it is possible, but not sure why it is not working at your end. Could it be that you run both development and runtime at the same time using different users? Because if one of the APEX users differs from the other then you are prompted to log on again with the other user.

How to encrypt credit card number in iPhone

I want to send credit card number through post method but the credit card number should be in encrypted form. How to encrypt it?
My code is:
NSString *fName = firstName.text;
NSString *lName = lastName.text;
NSString *phone = phoneNumber.text;
NSString *emailid = email.text;
NSString *cardNumber = creditCardNumber.text;
NSString *ID = particularEventPaidId;
NSString *postData = [NSString stringWithFormat:#"id=%#&firstname=%#&lastname=%#&phone=%#&email=%#&creditcard=%#",ID,fName,lName,phone,emailid,cardNumber];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"postLength is: %#",postLength);
NSURL *url = [NSURL URLWithString:#"http://cfcdi.org/eassociation/web-service/event-register.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSData *requestBody = [postData dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:requestBody];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
NSURLResponse *response;
NSError *requestError;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
if(requestError==nil)
NSLog(#"Error is nil");
else
NSLog(#"Error is not nil");
NSLog(#"success!");
In above I want to send credit card number in encrypted form.
Make sure you use a secure server when you prepare to launch your application (https://)
Look at some AES encryption examples and Apples CryptoExercise.
Apple's CryptoExercise
AES Encryption for an NSString on the iPhone