メインスレッドからバックグラウンドスレッドの実行ループを停止する方法を知っている人はいますか?
サーバーからファイルをダウンロードする機能を持つクラスがあります。メインスレッドから、バックグラウンドスレッドで関数 sendHttpRequest を呼び出して、サーバーからファイルをダウンロードしています。
[self performSelectorInBackground:@selector(sendHttpRequest:) withObject:file];
CFRunLoopRun(); を使用しました。コールバックを受け取り、CFRunLoopStop(CFRunLoopGetCurrent()); を使用してスレッドの終了と実行ループの停止を回避します。ダウンロード完了後。
しかし、データのダウンロード中にダウンロードを停止する必要があります。実行ループを停止するにはどうすればよいですか?
どんな助けでも....
これが私のコードです:
#import "HTTPHandler.h"
@implementation HTTPHandler
@synthesize fileName;
NSURLConnection *urlConnection;
NSMutableData *receivedData;
NSInteger receivedStatusCode;
- (id)initHttpHandler
{
self = [super init];
httpEvent = nil;
return self;
}
- (void)downloadFile:(NSString *)file
{
NSLog(@"Download file : %@", file);
fileName = file;
NSString *url = [NSString stringWithFormat:@"http://temporaryServerUrl&fileName=%@", fileName];
NSLog(@"URL : %@", url);
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0];
// create the connection with the request and start loading the data
[request setHTTPMethod:@"GET"];
[request setValue:[NSString stringWithFormat:@"text/plain,application/xml"] forHTTPHeaderField:@"Accept"];
urlConnection =[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (urlConnection)
{
// Create the NSMutableData to hold the received data.
receivedData = [[NSMutableData data] retain];
}
else
{
NSLog(@"HTTP connection failed to download file.");
}
NSLog(@"Run loop started");
CFRunLoopRun(); // Avoid thread exiting
NSLog(@"Run loop stoped");
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace (NSURLProtectionSpace *)protectionSpace
{
if ([NSURLAuthenticationMethodHTTPDigest compare:[protectionSpace authenticationMethod]] == NSOrderedSame)
{
return YES;
}
else
{
NSLog(@"Warning: Unsupported HTTP authentication method.");
}
return NO;
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge (NSURLAuthenticationChallenge *)challenge
{
if ([challenge previousFailureCount] == 0)
{
NSURLCredential *newCredential;
newCredential = [NSURLCredential credentialWithUser:@"admin" password:@"1234" persistence:NSURLCredentialPersistenceNone];
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
}
else
{
NSLog(@"Going to cancel the authentication challenge.");
[[challenge sender] cancelAuthenticationChallenge:challenge];
// inform the user that the user name and password in the preferences are incorrect
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// This method is called when the server has determined that it
// has enough information to create the NSURLResponse.
// It can be called multiple times, for example in the case of a
// redirect, so each time we reset the data.
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
[receivedData setLength:0];
receivedStatusCode = httpResponse.statusCode;
if (httpResponse.statusCode == 200)
{
NSLog(@"200 ok received");
}
else
{
// We can also add condition that status code >= 400 for failure.
NSLog(@"%d status code is received.", httpResponse.statusCode);
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData. receivedData is an instance variable declared elsewhere.
if ([urlConnection isEqual:connection])
{
[receivedData appendData:data];
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// release the connection, and the data object
[connection release];
// receivedData is declared as a method instance elsewhere
[receivedData release];
// inform the user
NSLog(@"Connection failed! Error domain - %@, error code %d, error discryption - %@", [error domain], [error code], [error localizedDescription]);
// stop a CFRunLoop from running.
CFRunLoopStop(CFRunLoopGetCurrent());
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if ([urlConnection isEqual:connection] && (receivedStatusCode == 200))
{
NSString *filePath;
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
filePath = [rootPath stringByAppendingPathComponent:fileName];
NSLog(@"File Path %@", filePath);
NSString *data = [[[NSString alloc] initWithData:receivedData encoding:NSISOLatin1StringEncoding] autorelease];
NSLog(@"Data : %@", data);
[data writeToFile:filePath atomically:YES encoding:NSISOLatin1StringEncoding error:NULL];
}
else
{
}
[urlConnection release];
[receivedData release];
// stop a CFRunLoop from running.
CFRunLoopStop(CFRunLoopGetCurrent());
}
@end