How to put value of NSUserdefault in URL - ios

I have this url NSURL *url = [NSURL URLWithString:#"http://site.com/ArcGIS/rest/services/POI_Data/MapServer/0/query?&where=ToegangsNr+%3D+5002&returnGeometry=true&outSR=4326&f=json"];
But i want to change the 5002 value in the string with the NSUserdefault _phonenumber.
How can i do this?
The other code of this function is:
ASIHTTPRequest *_request = [ASIHTTPRequest requestWithURL:url];
__weak ASIHTTPRequest *request = _request;
request.requestMethod = #"POST";
[request addRequestHeader:#"Content-Type" value:#"application/json"];
[request appendPostData:[json dataUsingEncoding:NSUTF8StringEncoding]];
// 5
[request setDelegate:self];
[request setCompletionBlock:^{
[MBProgressHUD hideHUDForView:self.view animated:YES];
NSString *responseString = [request responseString];
NSLog(#"Response: %#", responseString);
[self plotCrimePositions:request.responseData];
}];
[request setFailedBlock:^{
[MBProgressHUD hideHUDForView:self.view animated:YES];
NSError *error = [request error];
NSLog(#"Error: %#", error.localizedDescription);
}];

NSURL *url = [NSURL URLWithString:#"http://site.com/ArcGIS/rest/services/POI_Data/MapServer/0/query?&where=ToegangsNr+%3D+5002&returnGeometry=true&outSR=4326&f=json"];
NSString *urlString = [url absoluteString];
urlString = [urlString stringByReplacingOccurrencesOfString:#"5002" withString:[userDefaults objectForKey:#"_phoneNumber"]];
NSLog(#"%#",urlString);
url = [NSURL URLWithString:urlString];
NSLog(#"%#",url);
Hope it help.

Try this:
NSString *urlStr = [NSString stringWithFormat:#"http://site.com/ArcGIS/rest/services/POI_Data/MapServer/0/query?&where=ToegangsNr+%%3D+%#&returnGeometry=true&outSR=4326&f=json", [[NSUserDefaults standardUserDefaults] objectForKey:#"_phonenumber"]];
NSURL* url = [NSURL URLWithString:urlStr];

Related

Get current webview URL and login

I try to get the current URL because when I put bad login in my app, I have the login page displayed. I don't want this page to be displayed. So, I use the solution to get the current url and if this URL is http://www.example.com/account/login/ I want to create an action. But currently, when I try this solution, I have a null response.
NSString * currentURL = _loadscreen.request.URL.absoluteString;
if ([currentURL isEqualToString:#"http://www.example.com/account/login/"]) {
NSLog(#"WARNING");
}
else
{
NSLog(#"URL is %#",currentURL); <- return (null).
}
I use this code to auto-login users :
NSString *identifiant = [[NSUserDefaults standardUserDefaults] valueForKey:#"Identifiant"];
NSString *password = [[NSUserDefaults standardUserDefaults] valueForKey:#"Password"];
if((identifiant) && (password))
{
//Configure URL
NSString* host = #"http://www.example.com";
NSString* complement = #"/account/login";
NSString* user_name = [[NSUserDefaults standardUserDefaults] valueForKey:#"Identifiant"];
NSString* password = [[NSUserDefaults standardUserDefaults] valueForKey:#"Password"];
//Add URL + Folder
NSString *urlString = [NSString stringWithFormat:#"%#%#", host, complement];
//NSURL *url = [NSURL URLWithString:urlString];
NSURL *url = [NSURL URLWithString:urlString];
//NSURLRequest *request = [NSURLRequest requestWithURL:url];
//Add some informations POST
NSString *post = [NSString stringWithFormat:#"user_name=%#&password=%#&submit=submit", user_name, password];;
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length] > 0 && error == nil) [_loadscreen loadRequest:request];
else if (error != nil) NSLog(#"Error: %#", error);
}];
}
else
{
UIViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:#"login"];
[self presentViewController:controller animated:YES completion:nil];
}
NSString * currentURL = _loadscreen.request.URL.absoluteString;
if ([currentURL isEqualToString:#"http://www.example.com/account/login/"]) {
NSLog(#"WARNING");
}
else
{
NSLog(#"URL is %#",currentURL);
}
It's work fine, if user put the good id, if not, the login page is displayed but I don't want.

How will I convert this ASIFormDataRequest into AFNetworking?

This is the code Im using for ASIHTTPRequest I want to convert this to AFNetworking
NSURL *url = [NSURL URLWithString:path];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request addPostValue:self.theNewJob.jobID forKey:#"form[job_id]"];
[request addPostValue:thisJTF.typeFieldID forKey:#"form[jtf_id]"];
[request setFile:fullPath forKey:#"form[userfile]"];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
NSString *response = [request responseString];
if ([response isEqualToString:#"SUCCESS"]) {
// debugger
NSLog(#"signature file uploaded");
} else {
// debugger
NSLog(#"signature file upload Fail: %# response: %#", error, response);
}
}
You need to replace all methods manually. I looked for it and I think below link is good to start: http://door3.com/insights/ios-programming-converting-asihttprequest-afnetworking

ASIFormDataRequest returns NULL when trying to request a POST method

Hi im trying to make a POST request
my code:
NSURL *url = [NSURL URLWithString:urlString];
__weak ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setDelegate:self];
[request setRequestMethod:#"POST"];
[request setPostValue:#"JustinBieber" forKey:#"fname"];
[request setCompletionBlock:^{
NSString *result = [request responseString];
NSDictionary *dict = [result JSON];
NSLog(#"dict -%#",dict);
}];
[request setFailedBlock:^{
NSLog(#"error %#",[request error]);
}];
[request startAsynchronous];
when I run my code it returns a (null) value. My urlString is correct and the request didn't give me error also. I've tried it on web and returns a {"status":"success"} (it will return a dictionary with status successful or failed).
Use Like this. Hope this will help.
-(void)exe method
{
NSString *strURL=#"---your URL----";
NSURL *url=[NSURL URLWithString:strURL];
ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:url];
[request setRequestMethod:#"POST"];
[request setPostValue:#"JustinBieber" forKey:#"fname"];
[request setDelegate:self];
[request setTimeOutSeconds:60];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSError *error;
if(!error)
{
NSString *receivedString = [request responseString];
NSDictionary *dic = [receivedString JSONValue];
NSLog(#"output %#",dic);
}
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
}
Try with this code -
NSURL *url = [NSURL URLWithString:urlString];
__unsafe_unretained ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request setPostValue:#"JustinBieber" forKey:#"fname"];
[request setDelegate:self];
__block id jsonData;
[request setTimeOutSeconds:300];
[request setCompletionBlock:^(){
NSError *error = nil;
NSString *responseString = (request.responseString.length)?request.responseString:#"";
NSLog(#"%#",responseString);
NSData *responseData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
jsonData = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
if(error)
completionBlock(nil, error, task);
else
completionBlock(jsonData, error, task);
}];
[request setFailedBlock:^{
completionBlock(nil, request.error, task);
}];
[request startAsynchronous];
Might be it will helpfull for you.
Did you set your headers in the script that returns JSON correctly? Assuming you're using PHP:
header('Content-Type: application/json');
The default MIME-type is "text/plain", instead of "application/json". If you dont set the MIME-type correctly you're basicly trying to parse the whole document.
So instead of:
{"status":"success"}
You are most likely trying to parse:
<html>
<head></head>
<body>{"status":"success"}</body>
</html>
-(void)exe method
{
NSString *strURL=#"---your URL----";
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:strURL]];
[request setDelegate:self];
[request setRequestMethod:#"POST"];
[request setPostValue:#"JustinBieber" forKey:#"fname"];
[request setTimeOutSeconds:60];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSString *receivedString = [request responseString];
NSLog(#"output %#",receivedString );
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSString *receivedString = [request responseString];
NSLog(#"output %#",receivedString );
}

NSMutableURLRequest transform to ASIFormDataRequest

I have writen the fellowing code:
NSString *urlString = [NSString stringWithFormat:ADDRESS,action];
postStr = #"user_name=Thomas Tan&phone=01234567891&password=123456";
NSData *myRequestData = [NSData dataWithBytes:[postStr UTF8String] length:[postStr length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: myRequestData];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"%#",responseString);
it works well,but now I want to use asihttprequest framework,so how to change the above code,I have writen the code,but it can't get the correct result and just get the server error infomation.so what's the problem?
NSString *urlString = [NSString stringWithFormat:ADDRESS,action];
NSURL *url = [NSURL URLWithString:urlString];
ASIFormDataRequest *requeset = [ASIFormDataRequest requestWithURL:url];
[requeset setRequestMethod:#"POST"];
[requeset setPostValue:#"Thomas Tan" forKey:#"user_name"];
[requeset setPostValue:#"01234567891" forKey:#"phone"];
[requeset setPostValue:#"123456" forKey:#"password"];
[requeset startSynchronous];
NSError *error = [requeset error];
if (!error) {
NSString *re = [requeset responseString];
NSLog(#"%#",re);
}
NSLog(#"%#",error);
thank you in advance.
UPDATE:
NSString *urlString = [NSString stringWithFormat:ADDRESS,action];
NSURL *url = [NSURL URLWithString:urlString];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request appendPostData:[#"user_name=Thomas Tan&phone=01234567891&password=123456" dataUsingEncoding:NSUTF8StringEncoding]];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
NSString *re = [request responseString];
NSLog(#"%#",re);
}
NSLog(#"%#",error);
I use the above code ,It also can't get the same result,and error is not nil.
Your ASIHTTP code is not doing the same thing as your NSURLConnection code.
ASIFormDataRequest will automatically:
set the Content-Type header to application/x-www-form-urlencoded
URL-encoded your parameters
That's usually exactly what you want, but if you're getting the correct behavior with your NSURLConnection code and incorrect with ASIHTTP, then you need to change to a custom ASIHTTP POST and use ASIHTTPRequest, not ASIHTTPFormDataRequest, and then manually set the Conten-type back to application/x-www-form-urlencoded:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request addRequestHeader:#"Content-Type" value:#"application/x-www-form-urlencoded"];
[request appendPostData:[#"user_name=Thomas Tan&phone=01234567891&password=123456" dataUsingEncoding:NSUTF8StringEncoding]];
Doing this, and inspecting exactly what was sent to the server using Wireshark, I can see that the POST data sent is still not quite identical (ASIHTTP on the left, NSURLConnection on the right):
But the content type, length, and actual data is identical.
At this point, I'd expect your server to return the same result.
If it still doesn't, you can edit the ASIhTTP request parameters to match.

About ASIHTTPRequest send request

I'm using ASIHTTPRequest [request startAsynchronous] functon to send a request to my webservice api to login. If the request is ok, it returns a json value. Then I send another request to get user's info, but here I receive an error.
Here is my code:
-(void)login
{
[usernameTextField resignFirstResponder];
[passwordTextField resignFirstResponder];
username = [usernameTextField text];
password = [passwordTextField text];
if ( ([username length] == 0 ) || ([password length] == 0 ))
{
...
}
else
{
NSString *URL = [NSString stringWithFormat:#"https://xxx.xxx.xx.xx/FMS/Pages/Service/FMService.svc/Login?user=%#&pass=%#",username,password];
NSURL *requestURL = [NSURL URLWithString:URL];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:requestURL];
[request setValidatesSecureCertificate:NO];
[request setDelegate:self];
[request startAsynchronous];
}
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSError *error = [request error];
if (!error)
{
NSString *responseString = [request responseString];
NSDictionary *responseDict = [responseString JSONValue];
NSString *unlockCode = [responseDict objectForKey:#"d"];
if ( [unlockCode isEqualToString:#"successful"] )
{
NSURL *url = [NSString stringWithFormat:#"https://xxx.xxx.xx.xx/FMS/Pages/Service/FMService.svc/GetUserInfo?user=%#",username];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setValidatesSecureCertificate:NO];
[request startSynchronous];**//THERE IS AN ERROR**
NSError *error = [request error];
if (!error)
{
NSDictionary *responseDict = [responseString JSONValue];
NSString *realName = [responseDict objectForKey:#"RealName"];
NSLog(#"%#",realName);
}
}
else
{
//...
}
}
else
{
NSLog(#"%#",[error description]);
}
}
And there is an error:
[__NSCFString absoluteURL]: unrecognized selector sent to instance
0x69ef4b0
Another error:
void SendDelegateMessage(NSInvocation*): delegate
(_selectionLayoutChangedByScrolling:) failed to return after waiting
10 seconds. main run loop mode: kCFRunLoopDefaultMode
This line is incorrect:
NSURL *url = [NSString stringWithFormat:#"https://xxx.xxx.xx.xx/FMS/Pages/Service/FMService.svc/GetUserInfo?user=%#",username];
It should be changed to:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://xxx.xxx.xx.xx/FMS/Pages/Service/FMService.svc/GetUserInfo?user=%#",username]];

Resources