ASIHTTPRequest crashing when setting delegate? - iphone

It will be probably a simple problem, but I have been staring on this for a while now and I can't find it!
I have a SOAPRequest class like following:
#interface SoapRequest : NSObject
#property (retain, nonatomic) NSURL *endPoint;
#property (retain, nonatomic) NSString *soapAction;
#property (retain, nonatomic) NSString *userName;
#property (retain, nonatomic) NSString *passWord;
#property (retain, nonatomic) NSString *postData;
#property (retain, nonatomic) NSObject *handler;
#property SEL action;
+ (SoapRequest*) create: (NSObject*) target endPoint: (NSString*) endPoint action: (SEL) action soapAction: (NSString*) soapAction postData: (NSString*) postData;
- (id)sendSynchronous;
- (void) send;
#end
Implementation like following:
#synthesize endPoint = _endPoint, soapAction = _soapAction, userName = _userName, passWord = _passWord, postData = _postData, action = _action, handler = _handler;
+ (SoapRequest*) create: (NSObject*) target endPoint: (NSString*) endPoint action: (SEL) action soapAction: (NSString*) soapAction postData: (NSString*) postData
{
SoapRequest *request = [[SoapRequest alloc] init];
request.endPoint = [NSURL URLWithString:endPoint];
request.soapAction = soapAction;
request.handler = target;
request.action = action;
request.postData = postData;
return [request autorelease];
}
And my send function:
- (void) send
{
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:self.endPoint];
[request setDelegate:self];
[request addRequestHeader:#"Content-Length" value: [NSString stringWithFormat:#"%d",[self.postData length]]];
[request addRequestHeader:#"Content-Type" value:#"text/xml"];
if(self.soapAction)
{
[request addRequestHeader:#"soapAction" value:self.soapAction];
}
[request appendPostData:[self.postData dataUsingEncoding:NSUTF8StringEncoding]];
[request startAsynchronous];
}
I do have the default ASIHTTPRequest methods to listen for error or finish, my finish looks as following:
- (void)requestFinished:(ASIHTTPRequest *)request
{
[self.handler performSelector:self.action];
}
The case is, it crashes when I want to make this class a delegate for the ASIHTTPRequest, [request setDelegate:self]. I figured it has something to do with the Autoreleasing in the first function. But I don't have any idea how to fix it!
Edit:
This is how I init my SoapRequest:
- (SoapRequest*) DefinedEntities: (id) _target action: (SEL) _action
{
// some data inits
SoapRequest *request = [SoapRequest create: _target endPoint:endPoint action:_action soapAction:soapAction postData:xmlString];
[request send];
return request;
}
And this i init as following:
Metadata *service = [[Metadata alloc] init];
[service DefinedEntities:self action:#selector(MetadataFinished:)];

Had the same problem like you. The problem is, it gets deallocated before the delegate method gets called. Simply put a retain in your start method and a release in your finished method (and don't forget to release it in the error methods). This will let the object at life as long as the request is performing.

Please post the code where you're creating the instance of a SOAPRequest object using:
+ (SoapRequest*) create: (NSObject*) target endPoint: (NSString*) endPoint action: (SEL) action soapAction: (NSString*) soapAction postData: (NSString*) postData;
You may need to retain it. As an aside, you should use 'id' instead of NSObject* for your target parameter, as your target will not be an instance of NSObject (it will be a subclass) of sorts.

If the crash only occurs when you set self (SOAPRequest) as the delegate, are you sure that self isn't being deallocated (then the bad access occurs when the ASIHTTPRequest calls the did finish on its delegate which no longer exists).
- (SoapRequest*) DefinedEntities: (id) _target action: (SEL) _action
{
// some data inits
SoapRequest *request = [SoapRequest create: _target endPoint:endPoint action:_action soapAction:soapAction postData:xmlString];
[request send];
return request;
}
When you do this, request is autoreleased and you should make sure it is retained by someone until the ASIHTTPRequest it sent has finished or failed.

Retaining was indeed a good option, I found some typo's in my code and figured out what i did wrong already.
I had to do with the class in-between:
- (SoapRequest*) DefinedEntities: (id) _target action: (SEL) _action
{
// some data inits
SoapRequest *request = [SoapRequest create: _target endPoint:endPoint action:_action soapAction:soapAction postData:xmlString];
[request send];
return request;
}

Related

Error in set NSString property from another class

i have a problem passing a string to another UIViewController and then open this UIViewController, this is what i do:
.h
#import <UIKit/UIKit.h>
#interface BroswerViewController : UIViewController
#property (retain, nonatomic) IBOutlet UIWebView *myBrowserView;
#property (nonatomic, retain) NSString * myString;
#end
.m
#implementation BroswerViewController
#synthesize myBrowserView;
#synthesize myString;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewWillAppear:(BOOL)animated {
myString = [myString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://mywebsite/%#",myString]];
NSLog(#"%#",url);
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[myBrowserView loadRequest:request];
}
class where i call it:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (!self.myBroserViewController) {
self.myBroserViewController = [[[BroswerViewController alloc] initWithNibName:#"BroswerViewController" bundle:nil] autorelease];
}
[self.myBroserViewController setMyString:[NSString stringWithString:[stringArray objectAtIndex:indexPath.row]]];
[self.navigationController pushViewController:self.myBroserViewController animated:YES];
}
ok, so i pass a string to the BrowseViewController class, and then open the browseviewcontroller class and open the url with the string i have passed, and the first time work always, then i return back and pass another string and open the view and the second time works random, and the third time never, and i always receive a EXC_BAD_ACCESS on the line
#synthesize myString;
i don't know what i wrong...
Use self.myString rather than the plain variable when you reference it in viewWillAppear:. You're not getting the effect of the retain attribute when you use the variable directly rather than property notation.
I would add a couple of pointers to #Phillip Mills answer.
-On your init you should set myString to nil. This ensures that if it is released before being set somewhere else, it won't crash. Including if you use the setter which performs a release on it (you can release a nil reference).
-On your dealloc, you should release myString (unless you are using ARC).
-When you set it in viewWillAppear, you either need to do:
self.myString = [self.myString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
or
NSString *temp = myString;
[myString release];
myString = [[temp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] retain];
they both accomplish the same thing. Using self is easier though.
-Finally, I would use copy instead of retain unless you have a very specific reason to use retain. This ensures something else doesn't change it on you.
Best practices tells us use copy instead of retain in cases like this.
That's why:
myString = [myString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
changes the initial string too and next time you call this for already escaped string. That's why you get such weird behavior :)
Solution - change
#property (nonatomic, retain) NSString * myString;
ON
#property (nonatomic, copy) NSString * myString;
Using
self.myString
will solve it too, but it's still not a good practice... if, for example, your method will look like this:
NSURLRequest *request = [NSURLRequest requestWithURL:[self prepareUrl:self.myString]];
you still can catch very weird and hardly debugable artifacts.
in my code i change the instance variable name within my synthesize.
Here is what your code could look like
#implementation BroswerViewController
#synthesize myBrowserViewh = _myBrowserViewh;
#synthesize myString = _myString;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewWillAppear:(BOOL)animated {
self.myString = [self.myString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://mywebsite/%#",self.myString]];
NSLog(#"%#",url);
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[myBrowserView loadRequest:request];
}
at that point you would be forced to use either
self.myString = #"";
or reference the instance variable via
_myString = #"";
this would let the compiler help you find bugs like this.

How can I cancel an asynchronous call through NSURLConnection sendAsynchronousRequest?

I've got a web service call performing some validation on user input in real time. I'd like to use [NSURLConnection sendAsynchronousRequest] on the validation (which was introduced in iOS 5), but cancel it if the user changes the input field content in the mean time. What is the best way to cancel a current request?
It doesn't appear that there is a good way to do this. The solution seems to be to not use the new [NSURLConnection sendAsynchronousRequest] in situations in which you need to cancel the request.
I've managed to do this by placing the sendAsynchronousRequest method in a separate DownloadWrapper class, as follows:
//
// DownloadWrapper.h
//
// Created by Ahmed Khalaf on 16/12/11.
// Copyright (c) 2011 arkuana. All rights reserved.
//
#import <Foundation/Foundation.h>
#protocol DownloadWrapperDelegate
- (void)receivedData:(NSData *)data;
- (void)emptyReply;
- (void)timedOut;
- (void)downloadError:(NSError *)error;
#end
#interface DownloadWrapper : NSObject {
id<DownloadWrapperDelegate> delegate;
}
#property(nonatomic, retain) id<DownloadWrapperDelegate> delegate;
- (void)downloadContentsOfURL:(NSString *)urlString;
#end
#implementation DownloadWrapper
#synthesize delegate;
- (void)downloadContentsOfURL:(NSString *)urlString
{
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:TIMEOUT_INTERVAL];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length] > 0 && error == nil)
[delegate receivedData:data];
else if ([data length] == 0 && error == nil)
[delegate emptyReply];
else if (error != nil && error.code == ERROR_CODE_TIMEOUT)
[delegate timedOut];
else if (error != nil)
[delegate downloadError:error];
}];
}
#end
To utilise this class, I do the following, in addition to declaring the DownloadWrapper *downloadWrapper variable (in the interface declaration) and implementing the protocol methods which handles the response or a lack of one:
NSString *urlString = #"http://yoursite.com/page/to/download.html";
downloadWrapper = [DownloadWrapper alloc];
downloadWrapper.delegate = self;
[downloadWrapper downloadContentsOfURL:urlString];
Then I simply do the following to 'cancel' the connection when the view is about to disappear:
- (void)viewDidUnload
{
[super viewDidUnload];
downloadWrapper = nil;
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[downloadWrapper setDelegate:nil];
}
It's as simple as that. This would hopefully mimic the documented cancel method, which states that it does the following:
Once this method is called, the receiver’s delegate will no longer
receive any messages for this NSURLConnection.
I was concerned that this (somewhat naive) method means that the packets of data would still come through in response to our URL request - only that we're no longer 'listening in' as the delegate. But then I realised that once the URL request was sent through, there's really no way of stopping the response from coming back to us - we can only disregard it (if not at this level, then still at some lower level in the network hierarchy). Please correct me if I'm wrong.
Either way, hope this helps.

How do I repeat an ASIHTTPRequest?

Given the example code below:
// ExampleModel.h
#interface ExampleModel : NSObject <ASIHTTPRequestDelegate> {
}
#property (nonatomic, retain) ASIFormDataRequest *request;
#property (nonatomic, copy) NSString *iVar;
- (void)sendRequest;
// ExampleModel.m
#implementation ExampleModel
#synthesize request;
#synthesize iVar;
# pragma mark NSObject
- (void)dealloc {
[request clearDelegatesAndCancel];
[request release];
[iVar release];
[super dealloc];
}
- (id)init {
if ((self = [super init])) {
// These parts of the request are always the same.
NSURL *url = [[NSURL alloc] initWithString:#"https://example.com/"];
request = [[ASIFormDataRequest alloc] initWithURL:url];
[url release];
request.delegate = self;
[request setPostValue:#"value1" forKey:#"key1"];
[request setPostValue:#"value2" forKey:#"key2"];
}
return self;
}
# pragma mark ExampleModel
- (void)sendRequest {
// Reset iVar for each repeat request because it might've changed.
[request setPostValue:iVar forKey:#"iVarKey"];
[request startAsynchronous];
}
#end
# pragma mark ASIHTTPRequestDelegate
- (void)requestFinished:(ASIHTTPRequest *)request {
// Handle response.
}
- (void)requestFailed:(ASIHTTPRequest *)request {
// Handle error.
}
When I do something like [exampleModel sendRequest] from a UIViewController, it works! But, then I do [exampleModel sendRequest] again from another UIViewController and get:
Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '*** -[NSOperationQueue addOperation:]:
operation is finished and cannot be enqueued`
How can I fix this?
You shouldn't attempt to reuse the request object. It maintains state. Really designed to be disposed off after the request is over.
The design isn't as clean as the NSURLConnection, NSURLRequest, NSURLResponse classes (basically mashing all three into one and wrapping the low level core foundation classes underneath). It's still far better than using NSURLConnection in a vanilla fashion if you need to deal with low level HTTP stuff. If you don't, the high level classes have some advantages (like access to the same cache the UIWebView uses).
I think I found the answer: https://groups.google.com/d/msg/asihttprequest/E-QrhJApsrk/Yc4aYCM3tssJ
ASIHTTPRequest and its subclasses conform to the NSCopying protocol. Just do this:
ASIFormDataRequest *newRequest = [[request copy] autorelease];
[newRequest startAsynchronous];

Possible risk with asynchronous request and delegation

I would like to add to UIImageView the capacity to set an image with an url. As result I would like to do something like.
[anImageView setImageWithContentAtUrl:[NSURL URLWithString:#"http://server.com/resource.png"]];
So I created a category (code below).
NSString *kUserInfoImageViewKey = #"imageView";
NSString *kUserInfoActivityIndicatorKey = #"activityIndicator";
#implementation UIImageView (asynchronous)
#pragma mark -
- (void)setImageWithContentAtUrl:(NSURL *)imageUrl andActivityIndicator:(UIActivityIndicatorView *)activityIndicatorOrNil {
[activityIndicatorOrNil startAnimating];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:self forKey:kUserInfoImageViewKey];
[dict setValue:activityIndicatorOrNil forKey:kUserInfoActivityIndicatorKey];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:imageUrl];
request.delegate = self;
request.userInfo = dict;
[dict release];
[request startAsynchronous];
}
#pragma mark -
#pragma mark private
- (void)requestFinished:(ASIHTTPRequest *)aRequest {
// get concerned view from user info
NSDictionary *dictionary = aRequest.userInfo;
UIImageView *imageView = (UIImageView *)[dictionary valueForKey:kUserInfoImageViewKey];
UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView *) [dictionary valueForKey:kUserInfoActivityIndicatorKey];
[activityIndicator stopAnimating];
NSData *responseData = [aRequest responseData];
UIImage * image = [[UIImage alloc] initWithData:responseData];
imageView.image = image;
[image release];
}
- (void)requestFailed:(ASIHTTPRequest *)request {
}
An ASIHTTPRequest is created and launched with the image as delegate. I think there is a risk if image is deallocated before ASIHTTPRequest return a result.
So, maybe adding a retain in setImageWithContentAtUrl: and adding a release in requestFinished: and requestFailed: but I'm not very confident.
How is it possible to do such things ?
Regards,
Quentin
Quentin,
I regularly use ASIHTTPRequest for asynchronous calls, so I know where you're coming from here. Also, it's a pain to set up for the first time, but did you know that Three20 library's TTImageView (I think that's it) already does what you are trying to do? It will even cache the image locally so you don't have to load it every time. Anyway.
Your worry is correct: ASIHTTPRequest is a wrapper on an NSOperation object (it's actually a subclass), so the NSOperationQueue will retain ASIHTTPRequest as long as the request is active.
If your user changes the view (say, on a nav bar controller), which then deallocs your UIImageView, your code may crash when it tries to call back to the delegate. So, when you dealloc your image view, it's better to hold on to a reference to the request and then cancel it.
Rather than a category, this may be one of those times where subclassing is better - because you'd want to overwrite the dealloc method (this is how I've handled this issue).
First, add this property to your subclass:
#property (nonatomic, retain) ASIHTTPRequest *request;
Then add this line to your method so you can hold on to it:
self.request = request;
And finally, in your ASIHTTPRequest delegate methods, destroy the reference:
self.request = nil;
Then your dealloc could look like this:
- (void) dealloc
{
if (self.request)
{
// Cancels the NSOperation so ASIHTTPRequest doesn't call back to this
[self.request cancel];
}
[request release];
[super dealloc]
}

What could cause this difference in behaviour from iphone OS3.0 to iOS4.0?

I am getting a strange EXC_BAD_ACCESS error when running my app on iOS4. The app has been pretty solid on OS3.x for some time - not even seeing crash logs in this area of the code (or many at all) in the wild.
I've tracked the error down to this code:
main class:
- (void) sendPost:(PostRequest*)request {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSURLResponse* response;
NSError* error;
NSData *serverReply = [NSURLConnection sendSynchronousRequest:request.request returningResponse:&response error:&error];
ServerResponse* serverResponse=[[ServerResponse alloc] initWithResponse:response error:error data:serverReply];
[request.objectToNotifyWhenDone performSelectorOnMainThread:request.targetToNotifyWhenDone withObject:serverResponse waitUntilDone:YES];
[pool drain];
}
(Note: sendPost is run on a separate thread for each invocation of it. PostRequest is just a class to encapsulate a request and a selector to notify when complete)
ServerResponse.m:
#synthesize response;
#synthesize replyString;
#synthesize error;
#synthesize plist;
- (ServerResponse*) initWithResponse:(NSURLResponse*)resp error:(NSError*)err data:(NSData*)serverReply {
self.response=resp;
self.error=err;
self.plist=nil;
self.replyString=nil;
if (serverReply) {
self.replyString = [[[NSString alloc] initWithBytes:[serverReply bytes] length:[serverReply length] encoding: NSASCIIStringEncoding] autorelease];
NSPropertyListFormat format;
NSString *errorStr;
plist = [NSPropertyListSerialization propertyListFromData:serverReply mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&errorStr];
}
return self;
}
ServerResponse.h:
#property (nonatomic, retain) NSURLResponse* response;
#property (nonatomic, retain) NSString* replyString;
#property (nonatomic, retain) NSError* error;
#property (nonatomic, retain) NSDictionary* plist;
- (ServerResponse*) initWithResponse:(NSURLResponse*)response error:(NSError*)error data:(NSData*)serverReply;
This reliably crashes with a bad access in the line:
self.error=err;
...i.e. in the synthesized property setter!
I'm stumped as to why this should be, given the code worked on the previous OS and hasn't changed since (even the binary compiled with the previous SDK crashes the same way, but not on OS3.0) - and given it is a simple property method.
Any ideas? Could the NSError implementation have changed between releases or am I missing something obvious?
The setter calls [retain] on the new value, and [release] on the old value. One of those must be invalid (and non-nil) to cause the bad access.
sendPost doesn't initialize it's local error variable and if it is not set by NSURLConnection then it will contain garbage. Try initializing error to nil in sendPost.
Do you ever free serverResponse in the sendPost: message?
You init never calls its parent init. Try something like:
- (ServerResponse*) initWithResponse:(NSURLResponse*)resp error:(NSError*)err data:(NSData*)serverReply
{
if (self = [super init])
{
// ....
}
return self;
}