Issue in NSURL in Objective C - ios

I am trying to execute a async http request. but the call back log is not working. please analyze the code and suggest me the cause of this issue. I have seen the class examples in many places. But here i am calling it from a main function.
#interface HTTP : NSObject
#property (nonatomic,retain) NSMutableData *receivedData;
- (void) get : (NSString *) urlString;
#end
#implementation HTTP
#synthesize receivedData;
- (void)get: (NSString *)urlString {
NSLog ( #"GET: %#", urlString );
self.receivedData = [[NSMutableData alloc] init];
NSURLRequest *request = [[NSURLRequest alloc]
initWithURL: [NSURL URLWithString:urlString]
cachePolicy: NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval: 10
];
NSURLConnection *connection = [[NSURLConnection alloc]
initWithRequest:request
delegate:self
startImmediately:YES];
[connection start];
}
- (void)connection:(NSURLConnection*) connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"Response recieved");
}
- (void)connection:(NSURLConnection*) connection didReceiveData:(NSData *)data
{
NSLog(#"Data recieved");
NSString* responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[receivedData appendData:responseString];
}
#end
int main(const int c , char *arg[]){
HTTP *http = [[HTTP alloc] init];
[http get:#"http://www.apple.com"];
return 0;
}

Your program does not have a "run loop", therefore it terminates immediately after
[http get:#"http://www.apple.com"];
has returned, before any delegate functions are called. (Note that NSURLConnection works asynchronously.)
If this is for a stand-alone OS X application, you could to the following:
int main(const int c , char *arg[]){
HTTP *http = [[HTTP alloc] init];
[http get:#"http://www.apple.com"];
NSRunLoop *theRL = [NSRunLoop currentRunLoop];
while (shouldKeepRunning && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);
return 0;
}
where shouldKeepRunning is a (global) Boolean variable that is initially YES, and set to NO in
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
shouldKeepRunning = NO;
}
and also in connection:didFailWithError:. Or you add a Boolean property loading to your HTTP class.
If this is for an iOS application or a OS X Cocoa application, then you already have a run loop and don't have to add your own.

/*
Till the application finishes loading, the main thread is kept alive so that the delegate methods are called.
Hence the while loop below.
*/
while(!finished) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
Here is my working code.
#implementation HTTP
#synthesize receivedData,retStr,delegate;
- init {
if ((self = [super init])) {
receivedData = [[NSMutableData alloc] init];
}
return self;
}
- (void)get: (NSString *)urlString {
NSLog ( #"GET: %#", urlString );
self.receivedData = [[NSMutableData alloc] init];
NSURLRequest *request = [[NSURLRequest alloc]
initWithURL: [NSURL URLWithString:urlString]
cachePolicy: NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval: 10
];
NSURLConnection *connection = [[NSURLConnection alloc]
initWithRequest:request
delegate:self
startImmediately:YES];
while(!finished) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
if(!connection) {
NSLog(#"connection failed :(");
} else {
NSLog(#"connection succeeded :)");
}
}
- (void)post:(NSString*)urlString: (NSString*)body: (NSObject*) sender {
// POST
NSMutableString* requestURL = [[NSMutableString alloc] init];
[requestURL appendString:urlString];
NSMutableString* requestBody = [[NSMutableString alloc] initWithString:body];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: [NSString stringWithString:requestURL]]];
NSString* requestBodyString = [NSString stringWithString:requestBody];
NSData *requestData = [NSData dataWithBytes: [requestBodyString UTF8String] length: [requestBodyString length]];
[request setHTTPMethod: #"POST"];
[request setValue:#"text/html; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: requestData];
NSURLConnection *postConn= [[NSURLConnection alloc] initWithRequest:request delegate:sender];
/*
Till the application finishes loading, the main thread is kept alive so that the delegate methods are called.
Hence the while loop below.
*/
while(!finished) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
if(!postConn) {
NSLog(#"POST connection failed :(");
} else {
NSLog(#"POST connection succeeded :)");
}
}
// ====================
// Callbacks
// ====================
#pragma mark NSURLConnection delegate methods
- (NSURLRequest *)connection:(NSURLConnection *)connection
willSendRequest:(NSURLRequest *)request
redirectResponse:(NSURLResponse *)redirectResponse {
NSLog(#"Connection received data, retain count");
return request;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"Received response: %#", response);
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"Received %lu bytes of data", [data length]);
[receivedData appendData:data];
NSLog(#"Received data is now %lu bytes", [receivedData length]);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSRunAlertPanel(#"Error",[NSString stringWithFormat:#"Could not connect to server.Following error occured:\n\n%#", error], nil, nil, nil);
NSLog(#"Error receiving response: %#", error);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// Once this method is invoked, "responseData" contains the complete result
NSLog(#"Succeeded! Received %lu bytes of data", [receivedData length]);
NSString *dataStr=[[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding] ;
retStr = [NSString stringWithString:dataStr];
finished =TRUE;
// [self returnDcString:dataStr];
// NSLog(#"%#",dataStr);
if ([delegate respondsToSelector:#selector(didFinishDownload:)]) {
NSLog(#"Calling the delegate");
//NSString* dataAsString = [[[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding] autorelease];
// [delegate performSelector:#selector(didFinishDownload:) withObject: dataStr];
}
}
- (void)setDelegate:(id)val
{
delegate = val;
}
- (id)delegate
{
return delegate;
}
#end

Related

Asynchronous Connection Download Callback

I created a class customDownload with the following methods:
-(NSString *) getTextFromLink: (PreliteRequest *) requestDetails
asyncConnection: (BOOL) isAsync
callbackMethod: (SEL) methodToExecute {
mainRequest = requestDetails;
NSMutableURLRequest *postRequest = [[NSMutableURLRequest alloc] init];
NSURLRequest *getRequest = [[NSURLRequest alloc] init];
NSURLConnection *connection;
NSURLResponse * response = nil;
NSError * error = nil;
if ([[requestDetails getType] isEqualToString:#"POST"]) {
[postRequest setURL:[NSURL URLWithString:[requestDetails getUrl]]];
[postRequest setHTTPMethod:[requestDetails getType]];
[postRequest setValue:[requestDetails getPostLenght] forHTTPHeaderField:#"Content-Length"];
[postRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[postRequest setHTTPBody:[requestDetails getPostParameters]];
if (isAsync) {
tmpMethod = methodToExecute;
connection = [[NSURLConnection alloc] initWithRequest:postRequest delegate:self];
} else
downloadedData = (NSMutableData *)[NSURLConnection sendSynchronousRequest:postRequest returningResponse:&response error:&error];
} else {
getRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",[requestDetails getUrl],[requestDetails getGetParameters]]]];
if (isAsync) {
tmpMethod = methodToExecute;
connection = [[NSURLConnection alloc] initWithRequest:getRequest delegate:self];
} else
downloadedData = (NSMutableData *)[NSURLConnection sendSynchronousRequest:getRequest returningResponse:&response error:&error];
}
NSString *result=[[NSString alloc]initWithData:downloadedData encoding:NSUTF8StringEncoding];
return result;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
downloadedData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
[downloadedData appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSString *tmpResult = [[NSString alloc]initWithData:downloadedData encoding:NSUTF8StringEncoding];
[self performSelector:tmpMethod withObject:tmpResult];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#"Connection error: %#",error);
}
In my view controller I declare the previous class and call the only method of that class getTextFromLink.
download = [[customDownload alloc] init];
[download getTextFromLink:request asyncConnection:YES callbackMethod:tmpSelector];
SEL tmpSelector = #selector(printResult:);
-(void) printResult:(NSString *) resultToPrint {
NSLog(#"Risultato: %#",resultToPrint);
}
I pass to getTextFromLink the tmpSelector as parameter because that is the method I would like to call as soon the getTextFromDownloadLink has finished its job.
Actually getTextFromLink execute an asynchronous connection.
What I'm trying to do is to execute something when the asyncronous connection finished to download datas.
I would like to create a callback custom class to do this.
Can anyone help me?
Rather than this selector model, generally people would use blocks for this. For example, define a typedef for your block:
typedef void(^PreliteRequestCompletionHandler)(NSString *string);
Since you're dealing with an asynchronous pattern, you might want to define a property which you can use to save this completion handler to call later:
#property (nonatomic, copy) PreliteRequestCompletionHandler completionHandler;
You can then change that selector parameter to be a block parameter:
-(NSString *) getTextFromLink: (PreliteRequest *) requestDetails
asyncConnection: (BOOL) isAsync
completionHandler: (PreliteRequestCompletionHandler)completionHandler {
self.completionHandler = completionHandler;
// do stuff
}
And then, when you want to call that completion block, you do something like:
NSString *result = ...;
if (self.completionHandler) {
self.completionHandler(result);
}
And then you can now use this new block parameter to your method:
download = [[customDownload alloc] init];
[download getTextFromLink:request asyncConnection:YES completionHandler:^(NSString *result) {
NSLog(#"Risultato: %#", result);
}];

app crashes on NSURLCONNECTION when multiple request

Hey guyz I have this issue regarding the NSUrlConnection where I initiate a request like this
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:URL_PACKAGE,2]]];
Communication *comm = [[Communication alloc] initWithUrlRequest:request];
comm.request_name = request_name;
comm.delegate = self;
[comm startAsynchronous];
[request release];
and then the response getting code is fine but as you can see I have created a communication class to make the connection and when I request with difference web services it
- (Communication *) initWithUrlRequest:(NSMutableURLRequest *)url_request {
self.request = url_request;
return self;
}
-(void)dealloc {
[super dealloc];
}
- (void) startAsynchronous {
responseData = [[NSMutableData data] retain];
NSLog(#"%#",[request URL]);
downloadConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
}
-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response {
[responseData setLength:0];
if ( [[self delegate] respondsToSelector:#selector(communication:didReceiveResponse:RequestName:)] ) {
[self.delegate communication:self didReceiveResponse:response RequestName:self.request_name];
}
}
-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data {
[responseData appendData:data];
if ( [[self delegate] respondsToSelector:#selector(communication:didReceiveData:RequestName:)] ) {
[self.delegate communication:self didReceiveData:data RequestName:self.request_name];
}
}
-(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error {
[self.delegate communication:self didFailWithError:error RequestName:self.request_name];
NSLog(#"%#", error);
}
-(void)connectionDidFinishLoading:(NSURLConnection*)connection {
NSString *responseString = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] autorelease];
[responseData release];
responseString = [responseString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
responseString = [responseString stringByReplacingOccurrencesOfString:#"+" withString:#" "];
responseString = [responseString stringByReplacingOccurrencesOfString:#"null" withString:#"\"\""];
[self.delegate communication:self didFinishWithString:responseString RequestName:self.request_name];
}
The error is
2013-07-30 13:55:46.994 Ipad Qld[3982:c07] *** -[Requests respondsToSelector:]: message sent to deallocated instance 0xa16b310

Uploading Big Image In Background Thread. [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I need to upload an Image To webservice. Below is the code snippet i have return to upload an image. The image size is very big (around 6Mb). I am Uploading that Image in Background Thread using GCD.
if([VSCore ConnectedToInternet ])
{
bgTask = [[UIApplication sharedApplication]beginBackgroundTaskWithExpirationHandler: ^{
dispatch_async(dispatch_get_main_queue(), ^{
//[application endBackgroundTask:self->bgTask];
//self->bgTask = UIBackgroundTaskInvalid;
});
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[vrs write:data toURI:URI];
[[UIApplication sharedApplication]endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
});
//
}
-(BOOL)write:(NSData *)data toURI:(NSString *)URI
{
BOOL retVal = NO;
NSString* requestDataLengthString = [[NSString alloc] initWithFormat:#"%d", [data length]];
NSRange range = [URI rangeOfString:#"http"];//Is http?
if(range.location != NSNotFound)
{
//Yes, http
NSMutableURLRequest *httpRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:URI]];
[httpRequest setHTTPMethod:#"POST"];
[httpRequest setHTTPBody:data];
[httpRequest setValue:#"application/xml" forHTTPHeaderField:#"Content-Type"];
[httpRequest setValue:requestDataLengthString forHTTPHeaderField:#"Content-Length"];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:httpRequest delegate:self];
[theConnection release];
[httpRequest release];
if (theConnection)
{
receivedData=[[NSMutableData data] retain];
retVal = YES;
}
else
{
NSError *error = [NSError alloc];
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
[error release];
retVal = NO;
}
}
return retVal;
}
now the problem i am facing is, if i try to upload the image in background Thread the request is not going to server ( I am checking the Log file on server). but if i upload Image in Main Thread the request is going to server (Just for testing purpose, I know that its not good idea to upload big images in main thread). So what am i doing wrong here ? is there any problem with Background Threading ? Plz Help me Out. Thanks in advance.
Instead of doing it on a background thread. you could create a class that does your net connections like this.
you'll just need to add in the fields to post your image.
- (void)send: (NSString *)urlString {
self.receivedData = [[NSMutableData alloc] init];
NSURLRequest *request = [[NSURLRequest alloc]
initWithURL: [NSURL URLWithString:urlString]
cachePolicy: NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval: 20
];
NSURLConnection *connection = [[NSURLConnection alloc]
initWithRequest:request
delegate:self
startImmediately:YES];
if(!connection) {
NSLog(#"connection failed :(");
} else {
NSLog(#"connection succeeded :)");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
//NSLog(#"Received response: %#", response);
[receivedData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
//NSLog(#"Received %d bytes of data", [data length]);
[receivedData appendData:data];
//NSLog(#"Received data is now %d bytes", [receivedData length]);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Error receiving response: %#", error);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// Once this method is invoked, "responseData" contains the complete result
//NSLog(#"Succeeded! Received %d bytes of data", [receivedData length]);
NSString *dataStr=[[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
NSLog(#"%#",dataStr);
}
you'll need this in the header:
#interface NetConnection : NSObject
{
NSMutableData *receivedData;
}
#property (nonatomic,retain) NSMutableData *receivedData;
#property (nonatomic,retain) NSString *callback;

NSURLConnection Hangs under certain conditions

I'm posting to a RESTful webservice and receiving a response, this works great if I'm getting back only a few records however there is a threshold where didReceiveData: stops being called (6 records) and it just hangs. (does not matter what records, just the number)
I can't seem to figure out why. I'm getting a status message of 200 application/json in didReceiveResponse: however that's the last I hear from my connection.
From other clients I can get the full data with any number of records so it's related to my NSURLConnection code.
See full NSURLConnection Post class below.
the .h
#import <Foundation/Foundation.h>
#import "MBProgressHUD.h"
#protocol PostJsonDelegate <NSObject, NSURLConnectionDelegate>
#optional
- (void) downloadFinished;
- (void) downloadReceivedData;
- (void) dataDownloadFailed: (NSString *) reason;
#end
#interface PostURLJson : NSObject {
NSMutableData *receivedData;
int expectedLength;
MBProgressHUD *HUD;
}
#property (strong, nonatomic) NSMutableData *receivedData;
#property (weak) id <PostJsonDelegate> delegate;
#property (assign, nonatomic) int expectedLength;
+ (id)initWithURL:(NSString *)url dictionary:(NSDictionary *)dictionary withDelegate:(id <PostJsonDelegate>)delegate;
#end
the .m
#import "PostURLJson.h"
#define SAFE_PERFORM_WITH_ARG(THE_OBJECT, THE_SELECTOR, THE_ARG) (([THE_OBJECT respondsToSelector:THE_SELECTOR]) ? [THE_OBJECT performSelector:THE_SELECTOR withObject:THE_ARG] : nil)
#implementation PostURLJson
#synthesize delegate;
#synthesize receivedData;
#synthesize expectedLength;
+ (id)initWithURL:(NSString *)url dictionary:(NSDictionary *)dictionary withDelegate:(id <PostJsonDelegate>)delegate
{
if (!url)
{
NSLog(#"Error. No URL");
return nil;
}
PostURLJson *postJson = [[self alloc] init];
postJson.delegate = delegate;
[postJson loadWithURL:url dictionary:dictionary];
return postJson;
}
- (void)loadWithURL:(NSString *)url dictionary:(NSDictionary *)dictionary
{
[self setExpectedLength:0];
receivedData = [[NSMutableData alloc] init];
NSError* error;
NSDictionary *tmp = [[NSDictionary alloc] initWithDictionary:dictionary];
NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
NSString *someString = [[NSString alloc] initWithData:postdata encoding:NSASCIIStringEncoding];
NSLog(#"%#",someString);
NSString *postLength = [NSString stringWithFormat:#"%d", [postdata length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setTimeoutInterval:10.0f];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postdata];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
[self setLoadingModeEnabled:YES];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse *) response;
int errorCode = httpResponse.statusCode;
NSString *fileMIMEType = [[httpResponse MIMEType] lowercaseString];
NSLog(#"%d",errorCode);
NSLog(#"%#",fileMIMEType);
[receivedData setLength:0];
// Check for bad connection
expectedLength = [response expectedContentLength];
if (expectedLength == NSURLResponseUnknownLength)
{
NSString *reason = [NSString stringWithFormat:#"Invalid URL"];
SAFE_PERFORM_WITH_ARG(delegate, #selector(dataDownloadFailed:), reason);
[connection cancel];
return;
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
SAFE_PERFORM_WITH_ARG(delegate, #selector(downloadReceivedData), nil);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
SAFE_PERFORM_WITH_ARG(delegate, #selector(downloadFinished), nil);
[self setLoadingModeEnabled:NO];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Something went wrong...");
HUD.labelText = #"Something went wrong...";
[self performSelector:#selector(didFailHideHud) withObject:nil afterDelay:2];
}
- (void)setLoadingModeEnabled:(BOOL)isLoading
{
//when network action, toggle network indicator and activity indicator
if (isLoading) {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
UIWindow *window = [UIApplication sharedApplication].keyWindow;
HUD = [[MBProgressHUD alloc] initWithWindow:window];
[window addSubview:HUD];
HUD.labelText = #"Loading";
[HUD show:YES];
} else {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[HUD hide:YES];
[HUD removeFromSuperview];
}
}
-(void)didFailHideHud
{
[HUD hide:YES];
[HUD removeFromSuperview];
}
#end
Edit Server was not giving back a valid length after a certain size triggering NSURLResponseUnknownLength which I had mistakenly not logged so I was not getting my "Invalid URL" message in the console.
if (expectedLength == NSURLResponseUnknownLength)
{
NSString *reason = [NSString stringWithFormat:#"Invalid URL"];
SAFE_PERFORM_WITH_ARG(delegate, #selector(dataDownloadFailed:), reason);
[connection cancel];
return;
}
Try this:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
[connection start];
Because if you run the connection in the NSDefaultRunLoopMode and there is UITableView scrolling, it will hang the connection delegate.
However your problem is different. Some servers will limit the number of simultaneous connections from a single client. If you are in the case, then the first connections would succeed and the others would hang until previous connections complete.

iOS: connectionDidFinishLoading

I need some help. I am calling the login function from another class,
// Login on server
- (BOOL) login:(NSString*) username password:(NSString*)password
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:subscribedAppsURL]];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connectionDict setObject:connection forKey:#"login"];
[connection release];
return true;
}
// delegate
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Finished Loading");
if (connection == [connectionDict objectForKey:#"login"]) {
[connection release];
//#TODO Here I want to function login to return true.
}
}
At the end of connectionDidFinishLoading I want to return the TRUE/ FALSE value in the function login. Does anyone have some suggestions? Thanks!
You can send your request synchronously like this:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:subscribedAppsURL]];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error != nil)
{
NSString *stringResponse = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Reponse:%#", response);
//Handle the response, possible just return true here:
}
else
{
NSLog(#"Error:%#", error.localizedDescription);
}
With the intent of using delegates:
//In Header
#protocol LoginCompletionDelegate
-(void) didCompleteAndIsLoggedIn:(BOOL) loggedIn;
#end
#property (nonatomic, assign) id<LoginCompletionDelegate> delegate;
//In implementation
- (BOOL) loginWithDelegate:(id<LoginCompletionDelegate>)target username:(NSString*) username password:(NSString*)password
{
delegate = target;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:subscribedAppsURL]];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connectionDict setObject:connection forKey:#"login"];
[connection release];
return true;
}
// delegate
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Finished Loading");
if (connection == [connectionDict objectForKey:#"login"]) {
[connection release];
//#TODO Here I want to function login to return true.
[delegate didCompleteAndIsLoggedIn:YES];
}
}
//There is another method that looks like this. I might have the signature a bit wrong
-(void) connection:(NSURLConnection*) connection didFailWithError:(NSError*) error
{
[delegate didCompleteAndIsLoggedIn:NO];
}

Resources