I implement the JSON Parsing as follow:
-(void)getallEvent
{
SBJSON *json = [SBJSON new];
json.humanReadable = YES;
responseData = [[NSMutableData data] retain];
NSString *service = #"/GetAllVenue";
NSString *str;
str = #"Calagary";
NSString *requestString = [NSString stringWithFormat:#"{\"CityName\":\"%#\"}",str];
//NSLog(#"request string:%#",requestString);
// NSString *requestString = [NSString stringWithFormat:#"{\"GetAllEventsDetails\":\"%#\"}",service];
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSString *fileLoc = [[NSBundle mainBundle] pathForResource:#"URLName" ofType:#"plist"];
NSDictionary *fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc];
NSString *urlLoc = [fileContents objectForKey:#"URL"];
urlLoc = [urlLoc stringByAppendingString:service];
//NSLog(#"URL : %#",urlLoc);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: urlLoc]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: requestData];
// self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
NSError *respError = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];
if (respError)
{
NSString *msg = [NSString stringWithFormat:#"Connection failed! Error - %# %#",
[respError localizedDescription],
[[respError userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Check your network connection" message:msg delegate:self cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[alertView release];
}
else
{
NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSDictionary *results = [[responseString JSONValue] retain];
//NSLog(#" %#",results);
NSString *extractUsers = [[results objectForKey:#"d"] retain];
NSDictionary *finalResult = [[extractUsers JSONValue] retain];
NSLog(#"Final Results : %#",finalResult);
listOfEvents = [finalResult objectForKey:#"List of Event details of given Venue"];
}
Using this code, it slow down the app. How can I parse the json in background?
*Is this right for Post Method? what is the difference between Post & Get Method?*
Is there any other way to json parsing?
You are using synchronous request which is executed on Main thread so if you need to do it in background use asynchronous loading.
POST METHOD:
The POST method generates a FORM collection, which is sent as a HTTP request body. All the values typed in the form will be stored in the FORM collection.
GET METHOD: The GET method sends information by appending it to the URL (with a question mark) and stored as A Querystring collection. The Querystring collection is passed to the server as name/value pair. The length of the URL should be less than 255 characters.
An HTTP GET is a request from the client to the server, asking for a resource.
An HTTP POST is an upload of data (form information, image data, whatever) from the client to the server.
Check this answer for more details : what-is-the-difference-between-post-and-get
You are making synchronous communication request which slows down the application. You should make the asynchronous request to keep your app responsive.
It is not having any concern with parsing JSON data.
I would recommend using AFNetworking in your context which will simplify the connection management, background queue execution and parsing of the JSON you are getting back form the server.
The code example below will create an HTTP client with a base URL (<hostname>) and get a JSON payload from a given path. The network request runs in the background and runs a given block when completing
httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
// set the type to JSON
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
[httpClient setDefaultHeader:#"Accept" value:#"application/json"];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
// Activate newtork indicator
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
// Request the <path> from the server and parse the response to JSON
// this calls a GET method to <hostname>/<path>
[httpClient getPath:<your path> parameters:Nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
// responseObject is a JSON object here
//
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// handle error
}];
Get: With the get method the value is send through the query string appended with the url. So you can see the the name, value, description on the addressbar when the page display in the browser.
Post: This method transfer the information through the complete form. You can not see the detail description on the addresss bar. When the page display.
NSString *myUrlString =[NSString stringWithFormat: #"your url];
NSString *postdata=[NSString stringWithFormat:#"emailId=%#&password=%#,username,password];
NSLog(#"%#",postdata);
//create a NSURL object from the string data
NSURL *myUrl = [NSURL URLWithString:myUrlString];
//create a mutable HTTP request
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:myUrl];
//sets the receiver’s timeout interval, in seconds
[urlRequest setTimeoutInterval:30.0f];
//sets the receiver’s HTTP request method
[urlRequest setHTTPMethod:#"POST"];
//sets the request body of the receiver to the specified data.
[urlRequest setHTTPBody:[postdata dataUsingEncoding:NSUTF8StringEncoding]];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//Loads the data for a URL request and executes a handler block on an
//operation queue when the request completes or fails.
[NSURLConnection
sendAsynchronousRequest:urlRequest
queue:queue
completionHandler:^(NSURLResponse *response,
NSData *data,
NSError *error) {
if ([data length] >0 && error == nil){
//process the JSON response
//use the main queue so that we can interact with the screen
dispatch_sync(dispatch_get_main_queue(), ^{
[self parseResponse:data];
});
}
else if ([data length] == 0 && error == nil){
NSLog(#"Empty Response, not sure why?");
}
else if (error != nil){
NSLog(#"Not again, what is the error = %#", error);
}
}];
}
- (void) parseResponse:(NSData *) data
{
responseData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"JSON = %#", responseData);
NSLog(#"Response ==> %#", responseData;
Finally u get the response from that specific url .and what ever u wanted to it do ur own way.
Related
I was successful on getting a reply from the server with my post method however, I have problem with downloading the xml file data.
Here is my Post method (that I've searched in stackoverflow)
//We begin by creating our POST's body as an NSString, and converting it to NSData.
NSString *post = [NSString stringWithFormat:#"device_unique_key=%#&provision_type=c", deviceUniqueKey];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//Next up, we read the postData's length, so we can pass it along in the request.
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
//Now that we have what we'd like to post, we can create an NSMutableURLRequest, and include our postData.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://192.168.1.166/autoprovision/sip_setup/downloadSipSetup"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
//And finally, we can send our request, and read the reply by creating a new NSURLSession:
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
xmlData = data; //This is the data that I try to donwload as xml file.
NSLog(#"requestReply: %#", requestReply);
}] resume];
I have xmlData = data //from the dataTaskRequest
Then here is my code for saving the xmlData to the Document's Directory
// Display the network activity indicator
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
// Perform the request on a new thread so we don't block the UI
dispatch_queue_t downloadQueue = dispatch_queue_create("Download queue", NULL);
dispatch_async(downloadQueue, ^{
NSError* err = nil;
NSHTTPURLResponse* rsp = nil;
// Perform the request synchronously on this thread
NSData *rspData = [NSURLConnection sendSynchronousRequest:request returningResponse:&rsp error:&err];
// Once a response is received, handle it on the main thread in case we do any UI updates
dispatch_async(dispatch_get_main_queue(), ^{
// Hide the network activity indicator
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
if (rspData == nil || (err != nil && [err code] != noErr)) {
// If there was a no data received, or an error...
} else {
// Cache the file in the cache directory
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
path = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"init.xml"];
[[NSFileManager defaultManager] removeItemAtPath:path error:nil];
[xmlData writeToFile:path atomically:YES];
// Do whatever else you want with the data...
[self loadDataFromXML];
}
});
});
The problem is that the xmlData is not working when I parse it using NSXMLParser. I tried to use an xml file and put it inside my project and it parses the xml but the xmlData that I downloaded doesn't get parsed (parse delegates are not called). I think my way of downloading the file is wrong. Can someone help me?
I found the problem in my project. My codes were correct after all! I didn't see that the code that I followed uses NSCachesDirectory and when I call the xmlData I used NSDocumentDirectory that's why it doesn't get parsed.
I am sorry for this question. I am new to iOS.
I am working on xcode 7.1. I am calling a POST call on my Local server but I am getting this error. and I am not sure why. I have been trying and searching for couple of days now, but i couldn't find anything relevant. this is my code
NSString *myUrlString = [NSString stringWithFormat:#"%#%#/login",link,Entry ];
//create string for parameters that we need to send in the HTTP POST body
NSLog(#"My Url = %#",myUrlString);
NSMutableDictionary* postRequestDictionary = [[NSMutableDictionary alloc] init];
postRequestDictionary[#"email" ]= EmailIDTF.text;
postRequestDictionary[#"password" ]= PasswordTF.text;
NSLog(#"body = %#",postRequestDictionary);
NSData *json;
NSString *jsonString;
NSError *error;
// Dictionary convertable to JSON ?
if ([NSJSONSerialization isValidJSONObject:postRequestDictionary])
{
// Serialize the dictionary
json = [NSJSONSerialization dataWithJSONObject:postRequestDictionary options:NSJSONWritingPrettyPrinted error:&error];
// If no errors, let's view the JSON
if (json != nil && error == nil)
{
jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
NSLog(#"JSON: %#", jsonString);
}
}
//create a mutable HTTP request
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[myUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:60.0]; //sets the receiver’s timeout interval, in seconds
[urlRequest setTimeoutInterval:30.0f];
//sets the receiver’s HTTP request method
[urlRequest setHTTPMethod:#"POST"];
[urlRequest addValue:#"application/json" forHTTPHeaderField:#"Content-type"];
NSString *params = [NSString stringWithFormat:#"%#",jsonString];
NSLog(#"param = %#",params);
//sets the request body of the receiver to the specified data.
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
//allocate a new operation queue
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//Loads the data for a URL request and executes a handler block on an
//operation queue when the request completes or fails.
[NSURLConnection
sendAsynchronousRequest:urlRequest
queue:queue
completionHandler:^(NSURLResponse *response,
NSData *data,
NSError *error) {
if ([data length] >0 && error == nil){
//process the JSON response
//use the main queue so that we can interact with the screen
dispatch_async(dispatch_get_main_queue(), ^{
[self parseResponse1:data];
});
}
else if ([data length] == 0 && error == nil){
NSLog(#"Empty Response, not sure why?");
}
else if (error != nil){
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"Not again, what is the error = %#", error);
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Alert!" message:#"Please check that you are connected to internet." delegate:self cancelButtonTitle:#"I got it." otherButtonTitles: nil];
// spinnerview.hidden=YES;
[alert show];
});
}
}];
But all i am getting is this error
Error Domain=NSURLErrorDomain Code=-1012 "(null)" UserInfo={NSErrorFailingURLKey=http://xyz/login, NSErrorFailingURLStringKey=http://xyz/login, NSUnderlyingError=0x165a0f80 {Error Domain=kCFErrorDomainCFNetwork Code=-1012 "(null)" UserInfo={_kCFURLErrorAuthFailedResponseKey={url = http://xyz/login}}}}
and thing is that why is it giving "(null)"??
Please help me guys. Thanks in advance. 🙏
try after adding this key in your info.plist file:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Hope this helps.
pragma mark call web service with this code
NSString *myUrlString = [NSString stringWithFormat:#"%#%#/login",link,Entry ];
NSMutableDictionary* postRequestDictionary = [[NSMutableDictionary alloc] init];
postRequestDictionary[#"email" ]= EmailIDTF.text;
postRequestDictionary[#"password" ]= PasswordTF.text;
NSString *mystring=[self returnMeParameterString:postRequestDictionary];
NSURL *url = [NSURL URLWithString:myUrlString];
NSData *postData = [mystring dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[mystring length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse response, NSData data, NSError *connectionError) {
if(connectionError)
{
//error
}
else
{
//success
}
}];
pragma mark convert Dictionary to string
-(NSString*)returnMeParameterString:(NSDictionary *)params{
NSMutableString *paramstring = [[NSMutableString alloc] init];
NSMutableArray *keyArray = [[NSMutableArray alloc] init];
NSMutableArray *valueArray = [[NSMutableArray alloc] init];
for( NSString *aKey in [params allKeys] )
{
[keyArray addObject:aKey];
}
for( NSString *aValue in [params allValues] )
{
[valueArray addObject:aValue];
}
for (int k=0; k< keyArray.count; k++)
{
NSString *tempString;
if(k==0)
{
tempString = [NSString stringWithFormat:#"%#=%#",[keyArray objectAtIndex:k],[valueArray objectAtIndex:k]];
}
else
{
tempString = [NSString stringWithFormat:#"&%#=%#",[keyArray objectAtIndex:k],[valueArray objectAtIndex:k]];
}
[paramstring appendString:tempString];
}
return paramstring;
}
I have been stuck for almost a week now, I want to write to a SharePoint list, usin the rest api they provide. The api looks like this, http://site/_api/lists, and from here I can read and write depending on what I append to my url, I can read from the lists without any issues, but I have issues when I have to write.
I am supposed to send in Content-Type, Accept, X-requestDigest headers, and post body when I write to list. My code
NSString *deviceToken = [self getDeviceTokenFromCoreData];
NSString *postData = [NSString stringWithFormat:#"{ \"__metadata\": { \"type\": \"SP.Data.TestListItem\" }, \"Title\": \"Test Title\" }"];
NSData *methodBodyData = [postData dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSData *jsonString = [NSJSONSerialization JSONObjectWithData:methodBodyData options:0 error:&error];
NSString *acceptType = #"application/json;data=verbose";
NSString *requestDigest = _requestDigest;
NSURL *subscribeURL = [[NSURL alloc] initWithString:subscribeUrlString];
NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] initWithURL:subscribeURL];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody:jsonString];
[theRequest setValue:acceptType forHTTPHeaderField:#"Accept"];
[theRequest setValue:acceptType forHTTPHeaderField:#"Content-Type"];
[theRequest setValue:requestDigest forHTTPHeaderField:#"X-RequestDigest"];
This is where I construct my headers for the request. And this is how I handle the sending of the request
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:theRequest];
[operation setWillSendRequestForAuthenticationChallengeBlock:^(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge) {
// if (challenge.previousFailureCount == 0) {
NSLog(#"%#", challenge.protectionSpace);
NSURLCredential *creds = [NSURLCredential credentialWithUser:userName
password:userPass
persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:creds forAuthenticationChallenge:challenge];
} else {
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//Handle Success
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//Handle failure
}];
[operation start];
}
This happens after I have authenticated to sharepoint, I have noticed during debugging the setWillSendRequestForAuthenticationChallengeBlock never gets called again, looks like I need to send the authentication information via the headers now, which is what I think the request digest is for, but that doesnt help cause I still don't get through.
Error message I get from server is
<?xml version="1.0" encoding="utf-8"?>
<m:error
xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
<m:code>-2130575251, Microsoft.SharePoint.SPException</m:code>
<m:message xml:lang="en-US">The security validation for this page is invalid and might be corrupted. Please use your web browser's Back button to try your operation again.</m:message>
</m:error>
Thanks in advance :)
I can't find any answer for this in internet. I solved in a non recommended way. I made a requisition using GET method to a page in the sharepoint application. In the return, i have a tag with the request digest value.
I used this in this way, in my POST requisition:
[headers setValue:#"0x175481C0D6D79A7534A0992E528A5B7D36C80C41C01CBEE55EFB256FA99E1EF551F755BAAE07E692ADE757290F1ACCA11B560F71338DE4AA7781ADC90CDC5249,11 Jun 2015 18:22:18 -0000" forKey:#"X-RequestDigest"];
I am super new to coding so there is most likely a better way but this is how I solved this issue:
Write a method that retrieves the Request Digest from the site that looks like this:
-(NSDictionary *)digestValue
{
NSURL *url = [NSURL URLWithString:#"https://.../sites/_api/contextinfo"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSArray* cookieArray = [NSArray arrayWithObjects: rtFaCookie, fedAuthCookie, nil];
NSDictionary * cookieHeaders = [NSHTTPCookie requestHeaderFieldsWithCookies:cookieArray];
NSMutableDictionary * requestHeaders = [[NSMutableDictionary alloc] initWithDictionary: cookieHeaders];
[requestHeaders setObject: #"application/json;odata=nometadata" forKey: #"Accept"];
[requestHeaders setObject:#"application/json;odata=verbose" forKey:#"Content-Type"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"2" forHTTPHeaderField:#"Content-Length"];
[theRequest setAllHTTPHeaderFields:requestHeaders];
NSURLResponse *response;
NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
if (data) {
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return [jsonString JSONValue];
}
return nil;
}
Then call that method when you need a valid Request Digest with something like this:
//Method Pulls the most current Digest Value from SharePoint, and pulls out just the Form Digest Value Key.
NSDictionary * taskMetas = [self digestValue];
NSString *formDigestValue = [taskMetas objectForKey:#"FormDigestValue"];
I've search and try many different solutions but without luck.
I am trying to make a JSON Request to my server, it works for sure because I've tested it in PHP (simple call, it receives string name and string password and check into the database if the user is correct). The request should receive back a JSON with property "success" only (which could be "true" or "false").
Here is my code:
- (void)logonService:(NSString *) name widthArg2:(NSString *) password {
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://46.51.169.145/ios/index.php/user/login/"]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
//setting json fields
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
//prepare output data
NSString *in1;
NSDictionary *outputData = [NSDictionary dictionaryWithObjectsAndKeys:in1, #"success", nil];
NSError *error = nil;
NSData *jsonOutputData = [NSJSONSerialization dataWithJSONObject:outputData options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonOutputString = [[NSString alloc] initWithData:jsonOutputData encoding:NSUTF8StringEncoding];
//set json string to body data
NSData *requestInputBodyData = [jsonOutputString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody: requestInputBodyData];
//prepare input data
NSString *input = [NSString stringWithFormat:#"&name=%#&password=%#",name,password];
//Encode the post string using NSASCIIStringEncoding and also the post string you need to send in NSData format.
NSData *inputData = [input dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//calculate length of post data
NSString *inputLength = [NSString stringWithFormat:#"%d",[inputData length]];
//Set HTTP header field with length of the post data.
[request setValue:inputLength forHTTPHeaderField:#"Content-Length"];
//encode type
//[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
//add it to http body
[request setHTTPBody:inputData];
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(conn){
NSLog(#"Connection Successful");
}else{
NSLog(#"Connection could not be made");
}
}
The delegate DidReceiveData fires correctly but the result is always NIL:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSString *jsonResponseData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"RESULT1: %#", jsonResponseData);
[_responseData appendData:data];
}
Thank you, hope someone can help me!
thanks a lot for the comments, I finally fix it, and after that I decided to starting using a JSON library --> https://github.com/stig/json-framework/
This is how I finally have the code:
//prepare connection
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#user.php", _urlServer]];
NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
[data setObject:#"login" forKey:#"action"];
[data setObject:username forKey:#"username"];
[data setObject:password forKey:#"password"];
//start connection
// Create the request, if there is a connection going on just cancel it.
[_connection cancel];
//initialize new mutable data
NSMutableData *receivedData = [[NSMutableData alloc] init];
_receivedData = receivedData;
//initialize the url which will be fetched
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];
//set http method
[request setHTTPMethod:#"POST"];
//initialize a post data
NSString *dataString = [[NSString alloc] init];
for(id key in data) {
id value = [data objectForKey:key];
//keys string
NSString *newData = [NSString stringWithFormat:#"&%#=%#", key, value];
dataString = [dataString stringByAppendingString: newData];
}
//set request content type we MUST set this value.
[request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
//set post data of request
[request setHTTPBody:[dataString dataUsingEncoding:NSUTF8StringEncoding]];
//initialize a connection from request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
_connection = connection;
//NSLog(#"Sending request with parameters: %#", dataString);
//begin the connection
[_connection start];
And its working like a charm. Next step is to authenticate somehow, right now connection is open to the world.
I am having an issue trying to fetch JSON page from one of our company's site that requires authentication.
- http://xyz.com - requires authentication
- I need to fetch data from http://xyz.com/jsonpage1
- In View DidLoad, I send user and pwd for login to establish session
- Then, I have a button that would request JSON.
This sequence doesn't work (meaning if the session loading code is in a different routine than the json loading code). If I have both codes in same routine like a view didLoad, then it seems to recognize my credentials and get JSON back. Strange! What am I missing? How is supposed to work? I thought establishing the session will create the cookie one time and no need to bother with it again? Am I losing the cookie somehow when I click the button?
-(void)viewDidLoad
{
[self establishSession];
}
-(void)establishSession{
//
//Login Session
//
NSURL *url = [NSURL URLWithString:#"http://xyz.com/login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *post = [NSString stringWithFormat:#"username=%#&password=%#",#"abc",#"123"];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
[request setValue:[NSString stringWithFormat:#"%d",[postData length]] forHTTPHeaderField:#"Content-Length"];
[request setTimeoutInterval:15];
[request setHTTPBody:postData];
[request setHTTPMethod:#"POST"];
urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[urlConnection start];
}
- (IBAction)getJSON:(id)sender
{
NSError *error = nil;
resultsView.text =#"";
[self establishLoginSession]; //I have to have this line here to get it to work ?????
//get JSON
NSURL *jurl = [NSURL URLWithString:#"http://xyz.com/jsonPage1"];
NSData *jdata = [NSData dataWithContentsOfURL:jurl options:NSDataReadingUncached error:&error];
NSDictionary* jsonDict = [NSJSONSerialization
JSONObjectWithData:jdata //1
options:kNilOptions
error:&error];
NSString *dataString = [[NSString alloc]initWithData:jdata encoding:NSUTF8StringEncoding];
resultsView.text = dataString;
}
//Not sure if I need the cookie??
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse*) response;
NSDictionary *fields = [HTTPResponse allHeaderFields];
if([fields valueForKey:#"Set-Cookie"])
cookie = [fields valueForKey:#"Set-Cookie"];
}
You can only make one request with a NSURLConnection object, so you should create it right before you're making the request.