Transforming a String in a Array - iphone

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

Related

How to post json data to server [duplicate]

This question already has an answer here:
How to send json post values to a remote server and get the results with iOS 5?
(1 answer)
Closed 9 years ago.
In my iPhone app I want to send my data in JSON format.I have stored all the data in an dictionary.How to change dictionary data in JSON format and then send it to the serve using post method (I need to send to server only).
If your using SBJSON then using the code below you can create JSON string from NSDictionary.
SBJsonWriter *jsonWriter = [SBJsonWriter new];
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjects:values forKeys:keys];
NSString *jsonString = [jsonWriter stringWithObject:dict];
try it
NSMutableDictionary *Dict=[[NSMutableDictionary alloc] initWithObjectsAndKeys:str,#"str",str1,#"str1",Idstr,#"Idstr",nil];
NSError *error=nil;
NSData *Data=[NSJSONSerialization dataWithJSONObject:Dict options:NSJSONWritingPrettyPrinted error:&error];
NSMutableString *JsonString = [[NSMutableString alloc] initWithData:Data encoding:NSUTF8StringEncoding];
NSMutableString *urlstr=#"url"
NSURL *url=[NSURL URLWithString:urlstr];
NSMutableURLRequest *urlrequest=[NSMutableURLRequest requestWithURL:url];
NSString *urlbody=[NSString stringWithFormat:#"inputParam=%#",JsonString];
[urlrequest setHTTPBody:[Alerturlbody dataUsingEncoding:NSUTF8StringEncoding]];
[urlrequest setHTTPMethod:#"POST"];
[urlrequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Accept"];
[urlrequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlrequest setValue:[NSString stringWithFormat:#"%d", [urlbody length]] forHTTPHeaderField:#"Content-Length"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlrequest queue:queue completionHandler:^(NSURLResponse *response, NSData *Resdata, NSError *error)
{
NSError* error;
NSDictionary *jsondict = [NSJSONSerialization
JSONObjectWithData:Resdata //1
options:kNilOptions
error:&error];
//NSLog(#"jsondict:%#",jsondict);
}
else if ([Resdata length] == 0 && error == nil)
{
NSLog(#"Nothing was downloaded.");
else if (error != nil)
{
NSLog(#"Error happened = %#", error);
}
}];

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/ .

newby IOS: unable to redirect url

This is my first IOS project. Having a tough time getting login to work. The site has a meta_refresh to another url. I've tried to send another request to the url in the meta_refresh but then the app just hangs. I'm sure that I'm doing something wrong but I'm using XCode 4.4 so a lot of the NSURLConnection delegate methods have been deprecated.
Here's what I'm doing:
NSString *urlAsString = baseURL;
urlAsString = [urlAsString stringByAppendingString:#"?user[login]=username"];
urlAsString = [urlAsString stringByAppendingString:#"&user[password]=password"];
urlAsString = [urlAsString stringByAppendingString:#"&origin=splash"];
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:#"POST"];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
if([data length] > 0 && error == nil){
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"HTML = %#", html);
NSRange obj = [html rangeOfString:#"http-equiv=\"refresh\""];
NSInteger len = obj.length;
} else if([data length] == 0 && error == nil) {
NSLog(#"No data was returned.");
} else {
NSLog(#"Error happened = %#", error);
}
Here's what I'm getting:
Another question is that I've read that I should use asynchronous connection. The trouble is that I need the data scraped from the site to display on the screen. If I display the screen before the data is returned, then I won't have any data -- or am I not understanding how this works?
Thanks.
--Tony
I think that maybe you're a mixing stuff. You're setting a string url with GET values and then you set the HTTPMethod to POST and I don't know if that is going to work fine.
Here's a code that I have to send values with POST:
NSString *post = [NSString stringWithFormat:#"&user_login=%#&user_password=%#&origin=%#,username,password, splash];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:baseURL]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];

Sending form data via HTTP Post [Objective C]

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

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.