didReceiveData not getting called when downloading images - ios

I've seen many post on this topic, but none of them helped in resolving the problem. I am having a download.php file on webserver which I use for downloading images stored on the server. The php does this by splitting the task into two step.
The first step is I send the user info and the php returns the ids of images associated with the user. In the second step on basis of those ids I send another request to the same php page and request image of a particular id one by one.
This approach works well when used in html or in my android code, so I am sure that there's no issue in the php.
When I do send request to php from ios code, the first step of getting image ids works well, but requesting image doesn't work at all. The didReceieveData callback never gets called. Here's what I am doing -
- (void)downloadImages:(NSInteger)imageNo{
NSString *post = [NSString stringWithFormat:#"user=%#&download=%#&imageId=%d", userName, #"true",imageNo];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:[NSURL
URLWithString:#"MYWEBSERVER/download.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
currentDownMode = DOWN_IMAGE;
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
Here's what I am having in my php page -
function download()
{
global $folder_path, $user_id, $image_table, $sql_folder_path;
$fileID = $_POST["imageId"];
$sql="SELECT fileName,filePath FROM $image_table WHERE fileId='$fileID'";
$query = mysql_query($sql) or die($sql . ' - ' . mysql_error());
$row = mysql_fetch_array($query);
$im = file_get_contents("../" . $row[1] . $row[0]);
header('content-type: image/gif');
echo $im;
}

Related

objective-c json string to django-phonenumber-field "The phone number entered is not valid."

My iOS app needs to register new users with my website. One of the required fields is a phone number so I am using a django-phonenumber-field, PhoneNumberField, on the server in the model. My iOS code to send the POST request looks like this:
NSString *url = #"http://mywebsite.com/api/register";
NSString *post = #"name=test&email=test#test.com&phone_number=+15554443333&password=test";
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[post length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *con = [NSURLConnection connectionWithRequest:request delegate:self];
if(con) {
NSLog(#"Connection Successful");
} else {
NSLog(#"Connection could not be made");
}
Note: the "post" and "url" are usually passed in through a method call, but I just hard coded it in here for simplicity.
PhoneNumberField expects a number in international phone number format, which to the best of my knowledge is what I am using. No matter what I put in for phone_number I always get back {"phone_number":["The phone number entered is not valid."]} as the response. If I take out the phone_number from my model and use the same code (without phone_number=+15554443333) a new user gets registered on the server and everything works fine.
I have scavenged the internet high and low for my problem and can't find the solution anywhere. Does anybody know what I am doing wrong? Thanks.
The "name" in my model is a CharField and the "email" is a EmailField.
I figured out the problem. I needed to URL encode the string, meaning the plus sign in
NSString *post =#"name=test&email=test#test.com&phone_number=+15554443333&password=test";
needed to be a %2B. So the end string looks like
NSString *post =#"name=test&email=test#test.com&phone_number=%%2B15554443333&password=test";

NSURLRequest not posting values to a Codeigniter API

Good day,
I am trying to use a Codeigniter based API to connect with iOS and using NSURLRequest.
The API is in debugMode and for now it returns the same key value pair as json as the one that you are posting. I have tried posting the values to the link through postman and it works correctly, however when I post it through my iOS application, the json response is received but the array that should contain the post values is empty.
Here is the iOS Code snippet :
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#",BASEURL,service]];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSString * params = #"authkey=waris";
NSData * postData = [params dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];;
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSLog(#"Posting : '%#' to %#",params,url);
[connection start];
This is the response when I post the same parameters through postman ( A RESTFUL Client for Chrome )
{
"status": "1",
"data": {
"authkey": "warisali"
}
}
However when I query the same API from the above iOS Code I am getting this :
{
data = 0;
status = 1;
}
Any help on the matter will be highly appreciated!
I had same issue (not with CodeIgniter but with Ruby ...)
Try something like this, solved my problem.
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#",BASEURL,service]];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSDictionary *paramDict = #{#"authkey": #"waris"};
NSError *error = nil;
NSData *postData = [NSJSONSerialization dataWithJSONObject:paramDict options:NSJSONWritingPrettyPrinted error:&error];
if (error)
{
NSLog(#"error while creating data %#", error);
return;
}
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];;
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSLog(#"Posting : '%#' to %#",params,url);
[connection start];
I ended up using the ASIHttpRequest + SBJson combo and that worked like Charm!
After adding the ASIHttpRequest core classes and SBJson Classes to parse the JSON, I was able to achieve what I wanted !
The problem is that because of the way you're creating the connection, it will start immediately, before you've finished configuring the request. Thus, you're creating a mutable request, creating and starting the connection, then attempting to modify the request and then trying to start the request a second time.
You can fix that by changing the line that says:
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
To say:
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
Or, easier, just move the original instantiation of the NSURLConnection (without the startImmediately:NO) after you've finished configuring your request, and then eliminate the [connection start] line altogether.

POST request on iOS - not working

I have an iOS application which connects via OAuth 2.0 to Facebook. I would like to make a POST request which achieves the equivalent of this code in iOS:
curl -F 'access_token=...' \
-F 'message=Hello. I like this new API.' \
https://graph.facebook.com/[USER_ID]/feed
I found a nice tutorial online and I followed all the instructions, but I still can get my POST request to work. Here is my code:
NSString *post = post_text.text;
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *ready_post = [NSString stringWithFormat:#"https://graph.facebook.com/1313573269/feed?message=%#&access_token=CAACEdEose0cBAHgdZAon2EZBZCzjoLkhg7jrqvZAbliuoOQ2E2Exc4rZCAxPzeVEADwnQaNLYuG16Gq6q6LLLLLLLLVQ7LZAncXCc53qE2iyzleZAPXGajsgjnBTuo6YdJCZAxVGIYYD8sZCgQ9ypZCo0iOZBNuyrechBfee2yptlK9tmgdosZA7wrKg8ZD", postData];
[request setURL:[NSURL URLWithString:ready_post]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
As you can see I am hard coding the access token for the time being just as a test. But I cant seem to get my app to actually POST anything to Facebook.
Thanks, Dan.
You're trying to post a JSON to the GraphAPI - which you can't do.
Instead of that, you have to use parameters when posting (query string or HTTP request parameters).
See: Publish to Feed.

How to download a file from the server using a POST request or a more secure method without using a GET request for iOS application.

I do not want to use asihttp methods so is there a way to download a file from the server without having to use a get request? How to use a post request to download the file from the server?
Since the OP wants the answer regardless, I will use PHP for this.
iOS client side:
NSString *phpURLString = [NSString stringWithFormat:#"%#/getFile.php", serverAddress];
NSURL *phpURL = [NSURL URLWithString:phpURLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:phpURL];
NSString *post = [NSString stringWithFormat:#"filePath=%#", filePath];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%d", [post length]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]:
For the PHP side:
<?php
$filePath = htmlspecialchars($_POST['filePath']);
$fileData = file_get_contents($filePath);
echo $fileData;
?>
This is very basic. Also for the iOS side you would want to wrap that entire request in a code block that is run asynchronously in the background. You could use GCD for that. Once you have the file as responseData in iOS you can save the file to the local container and then do many things with it.

How to do authenticated service call

Hi I am trying to connect to some server which will use username and password as credentials..Following is the code I am using.
NSString post =[[NSString alloc] initWithFormat:#"userName=*&password=*"];
NSURL url=[NSURL URLWithString:#"******"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSLog(#"request:%#",request);
urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Here the problem is server is giving user invalid message.But the credentials which i am giving is fine.This username and password is not going in request object..can any one of you please help me..
You need to start with a string that holds your username & password. This will form the http POST body. You need to replace username_input_field & password_input_field with the correct input field names for the webserver. My advice is to use Firefox along with the httpFox extension to login to your webserver. httpFox will show you all the input field names for the request. There may also be extra hidden fields which you'll need to add too.
NSString *post = [NSString stringWithFormat:
#"username_input_field=%#&password_input_field=%#",username,password];
Add the username to the request header object, like so:
[request addValue:#"<username>" forKey:#"<username parameter>"]

Resources