leaks when using NSData, NSURL,NSMutableURLRequest,NSURLConnection and sendSynchronousRequest - nsurlconnection

I am getting the leak at this line in below code" NSData *returnData = [NSURLConnection ..........."
NSURL *finalURL = [NSURL URLWithString:curl];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:finalURL
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:10];
[theRequest setHTTPMethod:#"GET"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil];
BOOL enabled = [self getAutoGenerateObject:returnData];
return enabled;
please help me out of this problem.
Thank You,
Madan Mohan

You will need to release the returnData. That's why in Apple's examples in 'URL Loading Programming Guide / Using NSURLConnection', the returnData is assigned to an iVar and release in dealloc or connectionDidFinishLoading in the case of Asynchronous communication.
Depending what operation you are performing in you method getAutoGeneratedObject, but in theory it can take ownership there.
You could also mark returnData as autoreleased, but that is not always recommended especially if the response data is large.
NSURL *finalURL = [NSURL URLWithString:curl];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:finalURL
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:10];
[theRequest setHTTPMethod:#"GET"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil];
BOOL enabled = [self getAutoGenerateObject:returnData];
[returnData release];
return enabled;

Related

Simple example of NSURLSession with authentication

I have written a REST service that serves up some data. It is passcode protected.
I am trying to write a background process that will grab the data and stuff it into a sqlLite db I have in the app.
I did this initially without authentication using :
- (void) callWebService {
dispatch_sync(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:
scoularDirectoryURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
This worked fine but I don't think I can add authentication to that. If I can I would just use that.
What I am looking for is a nice, simple explanation of NSURLSession using user/password authentication.
I think your question is vague and underspecified. That said, here's one solution, from here:
-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)( NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
{
if (_sessionFailureCount == 0) {
NSURLCredential *cred = [NSURLCredential credentialWithUser:self.userName password:self.password persistence:NSURLCredentialPersistenceNone];
completionHandler(NSURLSessionAuthChallengeUseCredential, cred);
} else {
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
}
_sessionFailureCount++;
}
I strongly recommend that you read and re-read the Apple docs on this.
For me the following code works:
NSString *userName=#"user:";
NSString *userPassword=#"password";
NSString *authStr= [userName stringByAppendingString:userPassword];
NSString *url=#"http://000.00.0.0:0000/service.json";
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat: #"Basic %#",[authData base64EncodedStringWithOptions:0]];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
NSDictionary *theDictionary = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
NSDictionary *host = [theDictionary objectForKey : #"host"];
// json nested
self.label.text = [host objectForKey:#"key1"];
self.label.text = [host objectForKey:#"key2"];
regards

send parameter values and retrieve an xml file Xcode

In my current xcode project, I need to send parameter values to a url and need to retrieve an xml file based on the parameter values sent.
I tried the below code but it's not working:
(IBAction)myButtonClick:(id)sender
{
NSURL *oRequestURL =
[NSURL URLWithString:#"http://xyz .com/air/1.0/search?from=MAA&to=CJB&depart-date=2012-06-30&adults=2&children=2&infants=1&way=one&cabin-type=Economy&sort=asc"];
NSMutableURLRequest *oRequest = [[[NSMutableURLRequest alloc]init]autorelease];
[oRequest setHTTPMethod:#"POST"];
[oRequest setURL: oRequestURL];
NSMutableData *oHttpBody = [NSMutableData data];
[oHttpBody appendData:[#"This is HTTP Request body" dataUsingEncoding:NSUTF8StringEncoding]];
[oRequest setValue:[oHttpBody length] forHTTPHeaderField:#"Content-Length"];
NSError *oError = [[NSError alloc]init];
NSHTTPURLResponse *oResponseCode = nil;
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:oRequest returningResponse:oResponseCode error:oError];
if ([oResponseCode statusCode]> 200) {
NSLog(#"Status code is greater than 200");
}
NSString *strResult=[[NSString alloc]initWithData:oResponseData encoding:NSUTF8StringEncoding];
NSLog(#"The result is %s",strResult);
}
I have searched many sites and books but could not find a solution.
Would be of great help if a link to a tutorial or some other useful resource can be provided. Appreciate your great help.
Thank You.
Hi,
I have found the solution. The code is as below. Hope it helps someone else:)
- (IBAction)myButtonPressed:(id)sender
{
NSString *urlAsString = #"http://api.abc.com/air/1.0/search?from=MAA&to=CJB&depart-date=2012-09-30&adults=2&children=2&infants=1&way=one&cabin-type=Economy&sort=asc";
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setValue:#"2193141de2g7e2a34bb19bc3aa52b3b5" forHTTPHeaderField:#"X-XX-API-KEY"];
[urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:#"GET"];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection
sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length]>0 &&
error == nil)
{
NSString *html = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"HTML = %#", html);
}
else if ([data length]== 0 && error==nil) {
NSLog(#"Nothing was downloaded");
}
else if (error!= nil) {
NSLog(#"Error occured = %#", error);
}
}];
}

Why does my code break for one call to this method, but not another?

I have a Mac application that is supposed to fetch Twitter followers and friends for a given username and then, in turn, ask Twitter for the user NAMES for each of those returned UserIDs. As you can see below, I have a method that will call the Twitter API to get friends/followers (which works fine). It is the userNameForUserID:delegate: method that is causing me problems. I used to do these requests synchronously and return the NSString for the username right then. That (now commented out) line always broke, so I tried doing it with an NSURLConnection asynchronously. Still doesn't work. I don't understand why
[[NSString alloc] initWithContentsOfURL:...] works for the fetchFollowers... method, but not when I do it the EXACT SAME way in the other...
I put a break point on the line that used to alloc init the NSString with contents of URL, and when I step into it, it doesn't break, return, throw an exception, crash...nothing. It's as if that line just got stepped over (but my application is still blocked.
Any ideas? Much appreciated!
NSString * const GET_FOLLOWERS = #"https://api.twitter.com/1/followers/ids.json?cursor=-1&screen_name=";
NSString * const GET_FRIENDS = #"https://api.twitter.com/1/friends/ids.json?cursor=-1&screen_name=";
NSString * const GET_USER_INFO = #"https://api.twitter.com/1/users/show.json?user_id=";
#implementation TwitterAPI
+ (void)userNameForUserID:(NSNumber *)userID delegate:(id<UserNameDelegate>)delegate
{
NSURL *url = [NSURL URLWithString:[GET_USER_INFO stringByAppendingString:[userID stringValue]]];
// NSString *JSON = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:req queue:queue completionHandler:^(NSURLResponse *urlResponse, NSData *data, NSError *error) {
[delegate addUserNameToArray:data];
}];
}
+ (NSArray *)fetchFollowersWithUserName:(NSString *)userName
{
NSURL *url = [NSURL URLWithString:[GET_FOLLOWERS stringByAppendingString:userName]];
NSArray *followerIDs;
NSString *JSON = [[NSString alloc] initWithContentsOfURL:url encoding:NSASCIIStringEncoding error:nil];
if ([JSON rangeOfString:#"error"].location == NSNotFound)
followerIDs = [[JSON JSONValue] valueForKey:#"ids"];
return followerIDs;
}

XCode (iPhone) posting a JSON object to a cakePHP server?

I've got cakePHP running on my server. I'm trying to have my iPhone App post a JSON object to the server, then have the server echo it back. (Keeping it simple for now.) I've accessed the server plenty with normal URLs and gotten views back including JSON objects. This is my first attempt at posting JSON to the server. But it doesn't work. It always echos a null back.
In my iPhone App
NSDictionary* myDict = [NSDictionary dictionaryWithObjects:dictObjects forKeys:dictKeys];
NSData* jsonObject = [NSJSONSerialization dataWithJSONObject:myDict options:NSJSONWritingPrettyPrinted error:nil];
NSData *requestData;
// I've tried it both ways with this stringified or not
/*
NSString* jsonString = [[NSString alloc]initWithData:jsonObject encoding:NSUTF8StringEncoding];
requestData = [NSData dataWithBytes:jsonString length:[jsonString length]];
*/
requestData = [NSData dataWithData:jsonObject];
urlString = [NSString stringWithFormat:#"http://www.myServer.com/json_tests/echo_json"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:requestData];
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[urlRequest setValue:[NSString stringWithFormat:#"%d",[jsonObject length]] forHTTPHeaderField:#"Content-Length"];
currentConnection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
My CakePHP Server
This is in my controller file
public function echo_json() {
$rawData = $this->params['form'];
$decodedData = json_decode($rawData);
$this->layout = 'json';
$this->set(compact('rawData', 'decodedData'));
}
My view has ... echo $rawData; echo json_encode($decodedData);
But you know raw html source code doesn't get displayed here.

Session Maintenance for Login Page

My Requirement: I want to send login details(email, password) to server, have to maintain session for valid username.
How to create & maintain a session using "NSURLConnection" of iphone SDK?
If you found any Tutorials/Code snippets on this issue,Please post the corresponding linke here.
Advance thanks for your help.
NSString *urlString = [NSString stringWithFormat:#"http://www.mywebsite.com/login.php?email=username#yahoo.com&pwd=pass"];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection release];
[request release];

Resources