<rss version="2.0">
		<channel>
			<title>CocoaDev Forums - Can you use NSOperation as a Network Thread?</title>
			<lastBuildDate>Wed, 08 Sep 2010 02:22:56 -0700</lastBuildDate>
			<link>http://cocoadev.com/forums/</link>
			<description></description>
			<generator>Lussumo Vanilla 1.1.8</generator>
			<item>
		<title>Can you use NSOperation as a Network Thread?</title>
		<link>http://cocoadev.com/forums/comments.php?DiscussionID=9&amp;Focus=33#Comment_33</link>
		<guid isPermaLink="false">http://cocoadev.com/forums/comments.php?DiscussionID=9&amp;Focus=33#Comment_33</guid>
		<pubDate>Sat, 12 Jan 2008 22:13:20 -0800</pubDate>
		<author>Machx</author>
		<description>
			<![CDATA[Hello all,<br /><br />I am trying to confirm or debunk a feeling I have about NSOperation in that it can't be used for networking threads. Basically I am making a Cocoa App that connects to del.icio.us. When I thought about spawning the network threads I thought i'd try and experiment with NSOperation since I am on Leopard. I created a NSOperation subclass that in short creates a NSURLConnection with user credentials and assigns itself as a delegate to download the users last update time and return that. My Problem arises when I get to this bit of code inside my NSOperation subclasses main method<br /><br />// Run the runLoop for a few seconds to give the connection request a chance<br />[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:10]];<br /><br />after that 1 of 2 things happens... (1) the app crashes deep inside apples code or (2) it comes back with the html code of a page saying that I am not authenticated. When exploring the stack it looks like the application is behaving in such a way that NSURLConnection is getting started but when the data is finally being returned from del.icio.us it's like the memory for the thread has been yanked out from beneath the thread as if it just continued on regardless and ignored my code to keep running. I've tried several things to keep the thread running and everytime either (1) or (2) happens. I've been searching everywhere for an example of NSOperation being used in network operations, but can't so far and haven't found anything explicit in the documentation about network operations. <br /><br />In short can NSOperation be used as a network thread? If so am I trying to keep it running while it waits for a return response in a totally wrong way?<br /><br />If it's needed I'll post the full source code later, but for now I thought i'd find out the short answer to NSOperation being used in network threads first. Thank you very much for your help in advance!]]>
		</description>
	</item>
	<item>
		<title>Can you use NSOperation as a Network Thread?</title>
		<link>http://cocoadev.com/forums/comments.php?DiscussionID=9&amp;Focus=34#Comment_34</link>
		<guid isPermaLink="false">http://cocoadev.com/forums/comments.php?DiscussionID=9&amp;Focus=34#Comment_34</guid>
		<pubDate>Sat, 12 Jan 2008 22:49:57 -0800</pubDate>
		<author>reeses</author>
		<description>
			<![CDATA[Yes, you can do networking in an NSOperation.  I have done the same thing (but using NSURLDownload).  One difference is that I'm doing NSRunLoop#runMode:NSDefaultRunLoopMode beforeDate:&lt;date&gt; instead of runUntilDate:.<br /><br />I had a problem that took several hours to diagnose in http://cocoadev.com/forums/comments.php?DiscussionID=5&amp;page=1#Item_3.  Take a look and see if the errors look familiar to the ones you see.  What was ultimately happening was that I had been storing the NSURLResponse given in the #download:didReceiveResponse: delegate method in a property in my delegate class, and it appeared to be getting garbage collected.  I removed the reference and just stored the data I needed (content length) in a scalar field and the problems went away.]]>
		</description>
	</item>
	<item>
		<title>Can you use NSOperation as a Network Thread?</title>
		<link>http://cocoadev.com/forums/comments.php?DiscussionID=9&amp;Focus=40#Comment_40</link>
		<guid isPermaLink="false">http://cocoadev.com/forums/comments.php?DiscussionID=9&amp;Focus=40#Comment_40</guid>
		<pubDate>Sun, 13 Jan 2008 13:09:13 -0800</pubDate>
		<author>Machx</author>
		<description>
			<![CDATA[Well my problem is a bit different. I did try running it in the runloop mode mentioned above but I see 1 big problem either way I run it<br /><br />I see the NSURLConnection delegate method that says I received the data going off, but the authentication challenge never goes off and confuses the heck out of me. I've uploaded the full project to my site here ( http://www.1729.us/source/NetOperation.tbz ) if you want to run it.<br /><br />if you run the app you need to change<br /><br />userName = @&quot;__YOUR_DELICIOUS_ACT__&quot;;<br />password = @&quot;__YOUR_DELICIOUS_PASSWD__&quot;;<br /><br />to your own del.icio.us account name and password. Here is the source to the important parts of the system<br /><br />RFNetworkThread.h<br /><br />#import &lt;Cocoa/Cocoa.h&gt;<br /><br /><br />@interface RFNetworkThread : NSOperation<br />{<br />	NSData *urlData;<br />	NSString *userName;<br />	NSString *password;<br />	NSString *agent;<br />	NSString *header;<br />	NSString *apiUrl;<br />}<br /><br />@property(copy,readwrite) NSData *urlData;<br />@property(copy,readwrite) NSString *userName;<br />@property(copy,readwrite) NSString *password;<br />@property(copy,readwrite) NSString *agent;<br />@property(copy,readwrite) NSString *header;<br />@property(copy,readwrite) NSString *apiUrl;<br />@end<br /><br />RFNetworkThread.m<br /><br />#import &quot;RFNetworkThread.h&quot;<br /><br /><br />@implementation RFNetworkThread<br /><br />@synthesize urlData;<br />@synthesize userName;<br />@synthesize password;<br />@synthesize header;<br />@synthesize apiUrl;<br />@synthesize agent;<br /><br />- (BOOL)isConcurrent<br />{<br />	return YES;<br />}<br /><br />- (void)main<br />{<br />	urlData = nil;<br />	userName = @&quot;__YOUR_DELICIOUS_ACT__&quot;;<br />	password = @&quot;__YOUR_DELICIOUS_PASSWD__&quot;;<br />	agent = @&quot;NetOperation&quot;;<br />	header = @&quot;User-Agent&quot;;<br />	apiUrl = @&quot;https://api.del.icio.us/v1/posts/update&quot;;<br />	<br />	NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:apiUrl]<br />															  cachePolicy:NSURLCacheStorageNotAllowed<br />														  timeoutInterval:30];<br />	<br />	[urlRequest setValue:agent forHTTPHeaderField:header];<br />	<br />	NSURLCredential *userCredentials = [NSURLCredential credentialWithUser:userName<br />																  password:password<br />															   persistence:NSURLCredentialPersistencePermanent];<br />	<br />	NSURLProtectionSpace *space = [[NSURLProtectionSpace alloc] initWithHost:@&quot;https://api.del.icio.us&quot;<br />																		port:443<br />																	protocol:@&quot;https&quot;<br />																	   realm:@&quot;del.icio.us API&quot;<br />														authenticationMethod:nil];<br />	<br />	[[NSURLCredentialStorage sharedCredentialStorage] setCredential:userCredentials<br />												 forProtectionSpace:space];<br />	<br />	NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest<br />																  delegate:self];<br />	<br />	[connection start];<br />	<br />	<br />	// Run the runLoop for a few seconds to give the connection request a chance<br />	[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:10]];<br />	<br />	//while (self.urlData == nil) {<br />	//	NSLog(@&quot;Extending the run loop by 5 seconds&quot;);<br />	//	[[NSRunLoop currentRunLoop] runMode:@&quot;NSDefaultRunLoopMode&quot;<br />	//							 beforeDate:[NSDate dateWithTimeIntervalSinceNow:20]];<br />	//}<br />}<br /><br />- (void)download:(NSURLConnection *)download didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge<br />{<br />	NSLog(@&quot;ERROR: Cancelled the Authentication Challenge?&quot;);<br />}<br /><br />- (void)download:(NSURLConnection *)download didFailWithError:(NSError *)error<br />{<br />	NSLog(@&quot;ERROR: Download Failed with Error %@&quot;,error);<br />}<br /><br />- (void)download:(NSURLConnection *)download didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge<br />{<br />	if ([challenge previousFailureCount] &gt; 3)<br />	{<br />		NSLog(@&quot;ERROR: didReceiveAuthenticationChallege failed authentication too many times!&quot;);<br />		return;<br />	}<br />	<br />	NSLog(@&quot;Supplying User credentials&quot;);<br />	<br />	NSURLCredential *userCredentials = [NSURLCredential credentialWithUser:self.userName<br />																  password:self.password<br />															   persistence:NSURLCredentialPersistencePermanent];<br />	<br />	[[challenge sender] useCredential:userCredentials forAuthenticationChallenge:challenge];<br />}<br /><br />-(void) connection:(NSURLConnection *)conn didReceiveData:(NSData *)returnData<br />{<br />	if (returnData == nil || returnData.length == 0)<br />	{<br />		NSLog(@&quot;ERROR: Finished Downloading but there is no data!&quot;);<br />		return;<br />	}<br />	NSLog(@&quot;assigning urldata&quot;);<br />	self.urlData = returnData;<br />}<br /><br />@end]]>
		</description>
	</item>
	<item>
		<title>Can you use NSOperation as a Network Thread?</title>
		<link>http://cocoadev.com/forums/comments.php?DiscussionID=9&amp;Focus=307#Comment_307</link>
		<guid isPermaLink="false">http://cocoadev.com/forums/comments.php?DiscussionID=9&amp;Focus=307#Comment_307</guid>
		<pubDate>Mon, 18 Feb 2008 11:44:28 -0800</pubDate>
		<author>fenrir</author>
		<description>
			<![CDATA[not sure if you're still having this problem, but i had a similar problem of my delegate's not being around by the time data came back after i added in NSOperation.<br /><br />basically i was creating 20 - 30 NSURLConnections, which were locking up the main thread, so i added the tasks to NSOperationQueue as NSInvocationOperation objects (which may or may not be ideal for you).  <br /><br />anyway it never worked and it turned out that since i was doing the urlconnections asynchronously  things were getting collected before the data was returning.  i solved my problem by using NSURLConnections <br />&lt;code&gt;<br />sendSynchronousRequest:urlRequest returningResponse:&amp;urlResponse error:&amp;errorCode<br />&lt;/code&gt;<br /><br />and made the calls synchronously, since they were already threaded with NSOperationQueue anyway.  works better than i anticipated, but may or may not do what you want.]]>
		</description>
	</item>
	
		</channel>
	</rss>