iOS application connect to .NET Webservice by GET method - ios

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

Related

Telr Payment integration in iOS

I want to integrate Telr Payment integration in my App, I have gone through the DOC part and it seems like I have to request for enabling mobile API. If anyone has a demo of Telr integration in iOS, please feel free to share it. I am unable to find any demo regarding this Telr payment integration.
I am giving you my demo but Every time I am getting error and it says type -"E" Code-01. If any one here has any idea please help me out. Actually I am making a testing demo and it may be possible that I am passing some wrong params but in actual I don't know which params are wrong.
NSString *paramString = [NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<mobile:Body>\n"
"<store>%#</store>"
"<key>%#</key>"
"<device:Body>\n"
"<type>%#</type>"
"<id>%#</id>"
"<agent>%#</agent>"
"<accept>%#</<accept>"
"</device:Body>\n"
"<app:Body>\n"
"<name>%#</name>"
"<version>%#</version>"
"<user>%#</user>"
"<id>%#</<id>"
"</app:Body>\n"
"<tran:Body>\n"
"<test>%#</test>"
"<type>%#</type>"
"<class>%#</class>"
"<cartid>%#</<cartid>"
"<description>%#</description>"
"<currency>%#</currency>"
"<amount>%#</amount>"
"<ref>%#</<ref>"
"</tran:Body>\n"
"</mobile:Body>\n"
,#"123",#"XG32K#rBLn~BSm82",#"Simulator",#"xyzabc",#"",#"",#"Telr-Payment-Demo",#"1.0",#"Syscraft.Telr-Payment-Demo",#"",#"Test mode",#"PAYPAGE",#"",#"123",#"hello",#"AED",#"9.50",#""];
NSString *requestURL=#"https://secure.innovatepayments.com/gateway/mobile.xml";
NSURL *url=[NSURL URLWithString:requestURL];
NSData *data=[paramString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *mRequest = [[NSMutableURLRequest alloc] init];
[mRequest setURL:url];
[mRequest setHTTPMethod:#"POST"];
[mRequest setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[data length]] forHTTPHeaderField:#"Content-Length"];
[mRequest setValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[mRequest setHTTPBody:data];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *responseData1 = [NSURLConnection sendSynchronousRequest:mRequest returningResponse:&response error:&error];
if (error!=nil)
{
NSLog(#"Webservice Error==%#",error);
}
else
{
NSString *responseDic =[NSJSONSerialization JSONObjectWithData:responseData1 options:NSUTF8StringEncoding error:&error];
if (error!=nil)
{
NSLog(#"Webservice Error==%#",error);
}
else
{
NSLog(#"responseDic ======\n %#",responseDic);
}
}

SignalR ObjC returns "bad response code from server 403" when using WebSockets

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.

NSHTTPURLResponse release message sent to deallocated instance

I have the following code to get data from server;
-(void)loginForFaceBook
{
GTMOAuth2ViewControllerTouch *viewController;
viewController = [[GTMOAuth2ViewControllerTouch alloc]
initWithScope:#"https://www.googleapis.com/auth/plus.me"
clientID:#"27615...6qdi60qjmachs.apps.googleusercontent.com"
clientSecret:#"Fs8A...u2PH"
keychainItemName:#"OAuth2 Sample:
Google+"
delegate:self
finishedSelector:#selector(viewController:finishedWithAuth:error:)];
[[self navigationController] pushViewController:viewController
animated:YES];
}
- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
finishedWithAuth:(GTMOAuth2Authentication *)auth
error:(NSError *)error {
if (error != nil) {
// Authentication failed (perhaps the user denied access, or closed the
// window before granting access)
NSLog(#"Authentication error: %#", error);
NSData *responseData = [[error userInfo] objectForKey:#"data"]; //
kGTMHTTPFetcherStatusDataKey
if ([responseData length] > 0) {
// show the body of the server's authentication failure response
// NSString *str = [[NSString alloc] initWithData:responseData
// encoding:NSUTF8StringEncoding];
// NSLog(#"%#", str);
}
// self.auth = nil;
} else {
// NSString *authCode = [NSString alloc]in;
NSMutableURLRequest * request;
request = [[NSMutableURLRequest alloc] initWithURL:[NSURL
URLWithString:#"http://api.kliqmobile.com/v1/tokens"]
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:60] ;
NSLog(#"%#",auth);
NSLog(#"ho gya success %# :::: %# :::: %#", auth.accessToken,
auth.refreshToken, auth.code);
NSMutableURLRequest * response;
NSError * error;
request.URL = [NSURL URLWithString:#"http://api.kliqmobile.com/v1/tokens"];
NSString *post = [NSString stringWithFormat:#"
{\"token\":\"%#\",\"secret\":\"%#\",\"service\":\"%#\",\"handle\":\"%#\"}",
auth.accessToken,auth.code,#"google",nil];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded"
forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
error = nil;
response = nil;
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request
delegate:self];
[connection start];
}
I have implemented the NSURLConnection delegtes method and data is printing well like this
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
NSMutableURLRequest * response;
NSError * error;
NSLog(#"Did Receive Data %#", [[NSString alloc]initWithData:data
encoding:NSUTF8StringEncoding]);
NSMutableURLRequest * requestContacts;
requestContacts = [[NSMutableURLRequest alloc] initWithURL:[NSURL
URLWithString:#"http://api.kliqmobile.com/v1/contacts"]
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:60] ;
[requestContacts setHTTPMethod:#"GET"];
[requestContacts setAllHTTPHeaderFields:headers];
error = nil;
response = nil;
NSData* data1 = [NSURLConnection sendSynchronousRequest:requestContacts
returningResponse:&response error:&error];
NSLog(#"WE GET THE REQUIRED TOKAN DATA %# :: %# :: %#", [[NSString alloc]
initWithData:data1 encoding: NSASCIIStringEncoding], error ,response);
}
but after that my app get crashed and it is giving following error;
[NSHTTPURLResponse release]: message sent to deallocated instance 0xcb51070.
please suggest me how to do this.
A couple of thoughts:
What is the intent of your didReceiveData method? There are a bunch of issues here:
You really shouldn't be doing a synchronous network request in the middle of a NSURLConnectionDataDelegate method.
You shouldn't be doing synchronous requests at all, but rather do them asynchronously.
What is the connection between receiving data and your creation of this new request? You're not using the data in the request, so why do it here?
The typical pattern is:
The didReceiveResponse should instantiate a NSMutableData object in some class property.
The only function of didReceiveData should be to append the received data to the NSMutableData. Note, this method may be called multiple times before all the data is received.
In connectionDidFinishLoading, you should initiate any next steps that you take upon successful completion of the request. If you wanted to do start another asynchronous network request when the initial request is done, do that here.
In didFailWithError, you obviously handle any failure of the connection.
When you call connectionWithRequest, you should not use the start method. Only use start when you use initWithRequest:delegate:startImmediately: with NO for the startImmediately parameter. Otherwise the connection starts automatically for you and you're only starting it a second time.
Unrelated to your original question, but your creation of post string cannot be right. You're missing a parameter value. Even better, rather than creating JSON manually, use NSDictionary and then use NSJSONSerialization to make the NSData object containing the JSON from this dictionary. That's much safer:
NSDictionary *params = #{#"token" : auth.accessToken,
#"secret" : auth.code,
#"service" : #"google",
#"handle" : #""};
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
Clearly, supply whatever you need for the handle value.
A tangential process-related observation, but I'm wondering if you're taking advantage of everything Xcode offers. For example, your declaration of response as a NSMutableURLRequest but then using that as a parameter to sendSynchronousRequest should have generated a compiler warning. The same thing is true with your stringWithFormat for your post string (my third point). That should have generated a warning, too.
Neither of these are immediately relevant, but I wonder if you are failing to heed any other compile-time warnings. These warnings are your best friend when writing robust code and I would recommend resolving all of them. To go a step further, you should also run the project through the static analyzer ("Analyze" on "Product" menu, or shift+command+B), and resolve anything it points out, too.

iOS: using async

I currently have a screen with 2 tables. I'm getting the data synchronously and putting it on the screen. Code looks something like:
viewController.m
DBAccess_Error_T = [getList:a byCompanyID:1];
DBAccess_Error_T = [getList:b byCompanyID:2];
[self putListAOnScreen];
[self putListBOnScreen];
DBAccess.m
+ (DBAccess_Error_T)getList:(NSMutableArray*)a byCompanyID:(NSInteger)cID
{
// Pack this up in JSON form
[self queryDB:postData];
// Unpack and put it into variable a
}
+ (id)queryDB:(id)post
{
// Send request
// Get back data
}
I'm now trying to switch this over to async and I'm struggling. It's been hard even with website tutorials and documentations.
Since all of my database utilities are in separate files from the viewControllers, I'm not sure how I can use the didReceiveData and didReceiveResponse handlers. Also, since I have 2 arrays to fill for my 2 tables, how do I distinguish the difference in didReceiveData?
Instead, what I'm trying to do now is use sendAsynchronousRequest, but it seems I need to create an unpack function for every send function...let me know if I'm way off here...it looks something like:
viewController.m stays the same
DBAccess.m
+ (DBAccess_Error_T)getList:(NSMutableArray*)a byCompanyID:(NSInteger)cID
{
NSDictionary *post = /*blah blah*/
[self queryDB:post output:(a)];
}
+ (id)queryDB:(id)post output:(id)output
{
NSError *error;
NSData *jsonPayload = [NSJSONSerialization dataWithJSONObject:post options:NSJSONWritingPrettyPrinted error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody:jsonPayload];
[NSURLConnection sendAsynchronousRequest:request
queue:[[NSOperationQueue alloc] init]
completionHandler:^(NSURLResponse *response,
NSData *data,
NSError *error)
{
if ([data length] >0 && error == nil)
{
[self unpackDataForList:output data:data]; // This function needs to be different depending on which function called queryDB...the data will be unpacked in a different way
}
}
}
+ (void)unpackDataForList:(id)output data:(NSData*)data
{
// Do my unpacking here and stick it into 'output'.
}
How can I call a different unpackData function? are function pointers the right way to do this? Is this approach way off? Any tips would be greatly appreciated!
Have you ever looked at ASIHTTPRequest? It makes your life a lot easier by allowing you to use blocks. Here's an example of how to make an asynchronous request:
- (IBAction)grabURLInBackground:(id)sender
{
NSURL *url = [NSURL URLWithString:#"http://allseeing-i.com"];
__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setCompletionBlock:^{
// Use when fetching text data
NSString *responseString = [request responseString];
// Use when fetching binary data
NSData *responseData = [request responseData];
}];
[request setFailedBlock:^{
NSError *error = [request error];
}];
[request startAsynchronous];
}
You can find more information here:
http://allseeing-i.com/ASIHTTPRequest/

Send request to server iOS

I am trying to figure out how to send data to the server but currently without any progress.
What I know
On the server I have got some php script that return me data in response
for example with this URL: http://test.com/mobile_api/register
this script get next parameters:
id
name
info
time
so the string which I need looking like below
http://test.com/mobile_api/register?id=1000&name=alex&info=1.0&time=10000
What is best way to send this is string on the server
Now I'm trying to use ASIHTTPRequest. Can anybody send an example how to create correct request with my parameters.
This sample code should help you
-(void)sendRequest
{
int userId=10, time=10000;
NSString *name = #"ABC";
float info = 1.0;
NSString *urlString = [NSString stringWithFormat:#"http://test.com/mobile_api/register?id=%d&name=%#&info=%f&time=%d",userId,name,info,time];
ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
//You need to add ASIHTTPRequestDelegate in header(.h) file
[request setDelegate:self];
[request startAsynchronous];
}
- (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];
}

Resources