Sending form data via HTTP Post [Objective C] - iphone

I have a form data from an iphone app that needs to send HTTP Post variables to a URL.
The thing is, I've been told not to use setHTTPBody, but am unsure of how else to do it as every example I see uses setHTTPBody; even those that use POST methods.
To make things matters a little more complicated, the URL/webpage requires a submit=true and action=enquiry in the post variables.
Here's what I have so far.
NSString *formContactName = [self contactName];
NSString *formEmail = [self email];
NSString *formPhone = [self phone];
NSString *formComments = [self comments];
// The above data is fine, as explored here.
NSLog(#"formContactName = %#", formContactName);
NSLog(#"formEmail = %#", formEmail);
NSLog(#"formPhone = %#", formPhone);
NSLog(#"formComments = %#", formComments);
// Setup request
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:advertURL]];
[request setHTTPMethod:#"POST"];
// set headers
NSString *contentType = [NSString stringWithFormat:#"text/plain"];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
// setup post string
NSMutableString *postString = [[NSMutableString alloc] init];
[postString appendFormat:#"contactname=%#", formContactName];
[postString appendFormat:#"&email=%#", formEmail];
[postString appendFormat:#"&phone=%#", formPhone];
[postString appendFormat:#"&comments=%#", formComments];
[postString appendFormat:#"&submit=yes"];
[postString appendFormat:#"&action=enquiry"];
// I've been told not to use setHTTPBody for post variables, but how else do you do it?
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
// get response
NSHTTPURLResponse *urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponse
error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Response code: %d", [urlResponse statusCode]);
if ([urlResponse statusCode] >=200 && [urlResponse statusCode] <300)
{
NSLog(#"Response ==> %#", result);
}
[result release];
[error release];
I always get a 200 result, which is good. But the response back indicates that the Post variables are not getting through.
The response back has a field in it called "enquirysent" and its always blank. If the Post variables are successful, it should return a "1" or true statement.
"enquirysent": ""
Therefore, my question is: How do I force the HTTP-POST variables in the above request?
Thanks.

you can use ASIHTTPRequest to simplify:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:#"Ben" forKey:#"first_name"];
[request setPostValue:#"Copsey" forKey:#"last_name"];
[request setFile:#"/Users/ben/Desktop/ben.jpg" forKey:#"photo"];

Related

Trouble in sending data to server in ios

I am creating ios and android application which include chatting mechanisum.
I got problem in ios application when I am sending message to server. Sometime message send by ios device get repeated entry in server database. It happen rearly.
I am using ASIFormDataRequest class for communicating with server in ios.
My android app also using same API for communicating with server. Android app works properly
Code for sending message in ios is as follow.
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:urlString];
[request setRequestMethod:#"POST"];
for (NSString* key in dictionaryWithValue) {
[request setPostValue:[dictionaryWithValue objectForKey:key] forKey:key];
}
[request setTimeOutSeconds:60];
[request setDelegate:self];
[request setShouldContinueWhenAppEntersBackground:YES];
request.shouldAttemptPersistentConnection = NO;
[request startSynchronous];
Here dictionaryWithValue is NSDictonary which contain data in key value pair.
Is there in anything getting wrong in code?
Also in ios application, image is not uploading to server. it get connection time out.
For uploading image i have used following code
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setDelegate:self];
[request setRequestMethod:#"POST"];
[request setTimeOutSeconds:120];
[request setShouldContinueWhenAppEntersBackground:YES];
[request setUploadProgressDelegate:self];
[request setShouldAttemptPersistentConnection:YES];
[request setData:[parametersPOST objectAtIndex:2] withFileName:#"UserAvatarFile.png" andContentType:#"image/png" forKey:KEYAvatar];
[request startSynchronous];
NSString *fileName = [parametersPOST objectAtIndex:1];
[request setData:[parametersPOST objectAtIndex:2] withFileName:fileName andContentType:#"image/jpg" forKey:KEYAvatar];
[request setPostValue:[parametersPOST objectAtIndex:2] forKey:#"avatar"];
[request addPostValue:[parametersPOST objectAtIndex:2] forKey:#"avatar"];
[request setPostValue:[parametersPOST objectAtIndex:0] forKey:#"userid"];
[request setPostValue:fileName forKey:#"name"];
[request setPostValue:[parametersPOST objectAtIndex:3] forKey:#"token"];
[request startSynchronous];
Here parametersPOST is NSArray which contain data which i have to send to server.
+(NSDictionary *)getParsedDictonaryforUrlString:(NSString *)urlString withData:(NSData *)postData
{
NSString *newURL = urlString;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:newURL] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[request setHTTPBody: postData];
// get response
NSHTTPURLResponse *urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponse
error:&error];
if (responseData == nil)
{
// Check for problems
if (responseData != nil)
{
}
}
else
{
// Data was received.. continue processing
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Response code: %d", [urlResponse statusCode]);
if ([urlResponse statusCode] >=200 && [urlResponse statusCode] <300)
{
NSLog(#"Response ==> %#", result);
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:result error:parseError];
return xmlDictionary;
}
}
return nil;
}
This method may help to you

Do we need to give the request type either "json/xml"

My client is given one web service for my registration. I need to post the values.
I am using the following code to post:
-(IBAction)testingPurpose:(id)sender{
NSMutableDictionary *finalQuoteDict = [[NSMutableDictionary alloc] init];
[finalQuoteDict setValue:#"It is an Error Message" forKey:#"ErrorMsg"];
[finalQuoteDict setValue:#"json" forKey:#"ReturnVal"];
[finalQuoteDict setValue:#"john#live.com" forKey:#"Email"];
[finalQuoteDict setValue:#"David John" forKey:#"FullName"];
[finalQuoteDict setValue:#"2147483647" forKey:#"UserID"];
[finalQuoteDict setValue:#"john" forKey:#"UserName"];
[finalQuoteDict setValue:#"qqqqqq" forKey:#"UserPassword"];
SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init];
NSString *jsonRequest = [jsonWriter stringWithObject:finalQuoteDict];
jsonRequest = [jsonRequest stringByReplacingOccurrencesOfString:#"<" withString:#""];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#Register",MainUrl1,jsonRequest]];
NSLog(#"url is---%#",url);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSError* error = nil;
NSURLResponse* response;
NSData* result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *dataString=[[NSString alloc]initWithData:result encoding:NSUTF8StringEncoding];
NSMutableDictionary *getResponseDict = [[NSMutableDictionary alloc] init];
[getResponseDict addEntriesFromDictionary:[dataString JSONValue]];
}
But it throws an error says
"Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Unrecognised leading character\" UserInfo=0x856ac50 {NSLocalizedDescription=Unrecognised leading character}"
Please check the image i.e, to post the values..
Do we need to give the request type either "json/xml"
Thanks a lot in advance
Try to use this
Here httpMethod is "POST".
postData is all ur Post data with Key value same as for web service request.
aUrl is ur service url
-(void)WebService:(NSString *)httpMethod DataDictionary:(id)postData RequestAction:(NSString *)aUrl
{
// Check internet Connection
//Use Reachability class for this==============
Reachability *r = [Reachability reachabilityWithHostName:#"www.google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
{
NSLog("No Internet Connection Available");
return;
}
self.identifier = serviceIdentifier;
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:aUrl] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0 ];
NSLog(#"final request is %#",request);
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
//set body in JSON formate
[request setHTTPBody:[[self convertToJSON:postData] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *contentLength = [NSString stringWithFormat:#"%d",[[request HTTPBody] length]];
[request setValue:contentLength forHTTPHeaderField:#"Content-Length"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection)
{
self.responseData = [NSMutableData data]; //Its a mutable Data object
}
}
//Convert data into JSOn format
//use JSON classes for this
-(NSString *)convertToJSON:(id)requestParameters
{
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:requestParameters options:NSJSONWritingPrettyPrinted error:nil];
NSLog(#"JSON DATA LENGTH = %d", [jsonData length]);
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"JSON STR LENGTH = %d", [jsonString length]);
return jsonString;
}
//you will get response in NSURLConnection
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog("Failed to get Result......");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *jsonString = [[[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding] autorelease];
NSDictionary *aDic = [jsonString JSONValue];
NSLog("Your Response Data is ==>> %d",aDic);
}
Hope this will helps you
You don't need to supply json or xml in request type unless or until webservice requires it explicitly. It would be better if webservice handles it.
But i think problem is in parsing the response.
First make sure that dataString is not null or empty or you are getting some response from the server.
If it has some values then probably the return value or server response is not a valid JSON format.
You can validate json response by pasting it to the
http://jsonlint.com/ .

How to send json data in the Http request using NSURLRequest

I'm new to objective-c and I'm starting to put a great deal of effort into request/response as of recent. I have a working example that can call a url (via http GET) and parse the json returned.
The working example of this is below
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog([NSString stringWithFormat:#"Connection failed: %#", [error description]]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
//do something with the json that comes back ... (the fun part)
}
- (void)viewDidLoad
{
[self searchForStuff:#"iPhone"];
}
-(void)searchForStuff:(NSString *)text
{
responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.whatever.com/json"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
My first question is - will this approach scale up? Or is this not async (meaning I block the UI thread while the app is waiting for the response)
My second question is - how might I modify the request part of this to do a POST instead of GET? Is it simply to modify the HttpMethod like so?
[request setHTTPMethod:#"POST"];
And finally - how do I add a set of json data to this post as a simple string (for example)
{
"magic":{
"real":true
},
"options":{
"happy":true,
"joy":true,
"joy2":true
},
"key":"123"
}
Thank you in advance
Here's what I do (please note that the JSON going to my server needs to be a dictionary with one value (another dictionary) for key = question..i.e. {:question => { dictionary } } ):
NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:#"StoreNickName"],
[[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:#"user_question"], nil];
NSArray *keys = [NSArray arrayWithObjects:#"nick_name", #"UDID", #"user_question", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:#"question"];
NSString *jsonRequest = [jsonDict JSONRepresentation];
NSLog(#"jsonRequest is %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"https://xxxxxxx.com/questions"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
receivedData = [[NSMutableData data] retain];
}
The receivedData is then handled by:
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *question = [jsonDict objectForKey:#"question"];
This isn't 100% clear and will take some re-reading, but everything should be here to get you started. And from what I can tell, this is asynchronous. My UI is not locked up while these calls are made.
I struggled with this for a while. Running PHP on the server. This code will post a json and get the json reply from the server
NSURL *url = [NSURL URLWithString:#"http://example.co/index.php"];
NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:url];
[rq setHTTPMethod:#"POST"];
NSString *post = [NSString stringWithFormat:#"command1=c1&command2=c2"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];
[rq setHTTPBody:postData];
[rq setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:rq queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length] > 0 && error == nil){
NSError *parseError = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"Server Response (we want to see a 200 return code) %#",response);
NSLog(#"dictionary %#",dictionary);
}
else if ([data length] == 0 && error == nil){
NSLog(#"no data returned");
//no data, but tried
}
else if (error != nil)
{
NSLog(#"there was a download error");
//couldn't download
}
}];
I would suggest to use ASIHTTPRequest
ASIHTTPRequest is an easy to use
wrapper around the CFNetwork API that
makes some of the more tedious aspects
of communicating with web servers
easier. It is written in Objective-C
and works in both Mac OS X and iPhone
applications.
It is suitable performing basic HTTP
requests and interacting with
REST-based services (GET / POST / PUT
/ DELETE). The included
ASIFormDataRequest subclass makes it
easy to submit POST data and files
using multipart/form-data.
Please note, that the original author discontinued with this project. See the followring post for reasons and alternatives: http://allseeing-i.com/%5Brequest_release%5D;
Personally I am a big fan of AFNetworking
Most of you already know this by now, but I am posting this, just incase, some of you are still struggling with JSON in iOS6+.
In iOS6 and later, we have the NSJSONSerialization Class that is fast and has no dependency on including "outside" libraries.
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[resultStr dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
This is the way iOS6 and later can now parse JSON efficiently.The use of SBJson is also pre-ARC implementation and brings with it those issues too if you are working in an ARC environment.
I hope this helps!
Here is a great article using Restkit
It explains on serializing nested data into JSON and attaching the data to a HTTP POST request.
Since my edit to Mike G's answer to modernize the code was rejected 3 to 2 as
This edit was intended to address the author of the post and makes no
sense as an edit. It should have been written as a comment or an
answer
I'm reposting my edit as a separate answer here. This edit removes the JSONRepresentation dependency with NSJSONSerialization as Rob's comment with 15 upvotes suggests.
NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:#"StoreNickName"],
[[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:#"user_question"], nil];
NSArray *keys = [NSArray arrayWithObjects:#"nick_name", #"UDID", #"user_question", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:#"question"];
NSLog(#"jsonRequest is %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"https://xxxxxxx.com/questions"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil]; //TODO handle error
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
receivedData = [[NSMutableData data] retain];
}
The receivedData is then handled by:
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *question = [jsonDict objectForKey:#"question"];
Here's an updated example that is using NSURLConnection +sendAsynchronousRequest: (10.7+, iOS 5+), The "Post" request remains the same as with the accepted answer and is omitted here for the sake of clarity:
NSURL *apiURL = [NSURL URLWithString:
[NSString stringWithFormat:#"http://www.myserver.com/api/api.php?request=%#", #"someRequest"]];
NSURLRequest *request = [NSURLRequest requestWithURL:apiURL]; // this is using GET, for POST examples see the other answers here on this page
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if(data.length) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if(responseString && responseString.length) {
NSLog(#"%#", responseString);
}
}
}];
You can try this code for send json string
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ARRAY_CONTAIN_JSON_STRING options:NSJSONWritin*emphasized text*gPrettyPrinted error:NULL];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *WS_test = [NSString stringWithFormat:#"www.test.com?xyz.php&param=%#",jsonString];

Transforming a String in a Array

I'm having a little question here. I'm doing a login with a form, sending strings to a php, to return to me the final answer, "Error" or "OK".
But, i need to php returns a little bit more than it, like a name and etc, and i want to display this name in a label. So, for this, i'll need a array, correct?
So, how can i do this?
NSMutableURLRequest *request =
[[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:#"http://localhost/dev/mcomm/login.php"]];
[request setHTTPMethod:#"POST"];
NSString *postString = [[NSString alloc] initWithFormat:#"email=%#&pass=%#", email.text, senha.text];
[request setValue:[NSString
stringWithFormat:#"%d", [postString length]]
forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postString
dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc]
initWithRequest:request delegate:self];
//get response
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Response Code: %d", [urlResponse statusCode]);
if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300) {
NSLog(#"Response: %#", result);
}
Thanks!
it most situations, you would expect the response to be in XML or JSON.
If you have control, access to the API I would suggest you try and go that route instead of an Array

Creating an MJPEG Viewer Iphone

I'm trying to make a MJPEG viewer in Objective C but I'm having a bunch of issues with it.
First off, I'm using AsyncSocket(http://code.google.com/p/cocoaasyncsocket/) which lets me connect to the host.
Here's what I got so far
NSLog(#"Ready");
asyncSocket = [[AsyncSocket alloc] initWithDelegate:self];
//http://kamera5.vfp.slu.se/axis-cgi/mjpg/video.cgi
NSError *err = nil;
if(![asyncSocket connectToHost:#"kamera5.vfp.slu.se" onPort:80 error:&err])
{
NSLog(#"Error: %#", err);
}
then in the didConnectToHost method:
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{
NSLog(#"Accepted client %#:%hu", host, port);
NSString *urlString = [NSString stringWithFormat:#"http://kamera5.vfp.slu.se/axis-cgi/mjpg/video.cgi"];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
//set headers
NSString *_host = [NSString stringWithFormat:host];
[request addValue:_host forHTTPHeaderField: #"Host"];
NSString *KeepAlive = [NSString stringWithFormat:#"300"];
[request addValue:KeepAlive forHTTPHeaderField: #"Keep-Alive"];
NSString *connection = [NSString stringWithFormat:#"keep-alive"];
[request addValue:connection forHTTPHeaderField: #"Connection"];
//get response
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Response Code: %d", [urlResponse statusCode]);
if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300) {
NSLog(#"Response: %#", result);
//here you get the response
}
}
This calls the MJPEG stream, but it doesn't call it to get more data. What I think its doing is just loading the first chunk of data, then disconnecting.
Am I doing this totally wrong or is there light at the end of this tunnel?
Thanks!
Try loading the mjpeg in a UiWebView, it should be able to play it natively.
Assuming you have a UiWebView called "myWebView", something like this should work:
NSURLRequest* urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://kamera5.vfp.slu.se/axis-cgi/mjpg/video.cgi"]];
[myWebView loadRequest:urlRequest];
I hope that helps!
the main problem is that webkit never relase the data, so after a while it explode.
That would probably best be done with JavaScript since there isn't a good way to communicate with UIWebView otherwise.