connect というメソッドから URL のコンテンツを取得しようとしています。構成設定を読み取り、URL の取得を試みます。実行するには実行ループが必要なようです。私はそれが一度実行されるだけで完了すると思っていました。connect が呼び出されるたびに、この URL を 1 回取得する以外の理由で実行ループを実行する必要はないようです。これを行うより良い方法はありますか?
- (BOOL) connect
{
// read serverName and eventId from preferences
NSMutableArray* preferences;
preferences = [NSMutableDictionary dictionaryWithContentsOfFile:@"/tmp/wt.plist"];
// if these values aren't nil or blank
if ([preferences valueForKey:@"serverAddress"] && [preferences valueForKey:@"eventId"]) {
[self setServerAddress:@"172.16.28.210"];
[self setEventId:@"OT-3037009"];
} else{
// return some kind of error message
}
NSLog(@"VideoDataURL: %@", [self getVideoDataURL]);
// grab the URL and query the server
NSURL *myURL = [NSURL URLWithString:@"http://localhost"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:2];
__unused NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
[[NSRunLoop currentRunLoop] run];
return TRUE;
}
- (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.
// receivedData is an instance variable declared elsewhere.
[incomingData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
/*
* Called each time a chunk of data arrives
*/
NSLog(@"received %lu bytes", [data length]);
// Create a mutable data if it doesn't already exist
if (!incomingData) {
incomingData = [[NSMutableData alloc] init];
}
[incomingData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
/*
* Called if the connection fails
*/
NSLog(@"connection failed: %@", [error localizedDescription]);
incomingData = nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
/*
* Called when the last chunk has been processed
*/
NSLog(@"Got it all!");
NSString *string = [[NSString alloc] initWithData:incomingData encoding: NSUTF8StringEncoding];
incomingData = nil;
NSLog(@"response is: %@", string);
}