私はアプリケーションを持っていて、以前は .json で json データを取得していましdataWithContentsOfURL
た。
しかし、非同期の方法で取得する必要があるためです。
これを処理するために使用するようになったので、メソッドNSURLConnection
でステータスコード 200 を取得するだけで、有用なデータを受け取りませんが、呼び出されることはありません。そしてリターンで。didReceiveResponse
didReceiveData
connectionDidFinishDownloading
destinationURL
null
この問題が何を引き起こしているのかわかりません。助けていただければ幸いです。
代理人
#import "NetWorkToGuiDelegate.h"
@implementation NetWorkToGuiDelegate
@synthesize data;
@synthesize caller;
- (id) init: (SEL) pointer :(NSObject *) c;
{
doWhenDone = pointer;
self.caller = c;
data = [[NSMutableData alloc]init];
return self;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseText = [[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding];
NSLog(@"%@",responseText);
}
- (void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *)destinationURL
{
NSLog(@"post download finished");
data = [NSData dataWithContentsOfURL:destinationURL];
NSLog(@"data: %@",data);
NSLog(@"URLconnection %@", connection.currentRequest);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[caller performSelector:doWhenDone withObject:data];
#pragma clang diagnostic pop
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.data setLength:0];
NSHTTPURLResponse *resp= (NSHTTPURLResponsae *) response;
NSLog(@"got responce with status %d",[resp statusCode]);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d
{
NSLog(@"data recieved %@",d);
[self.data appendData:d];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", @"")
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:NSLocalizedString(@"OK", @"")
otherButtonTitles:nil] show];
NSLog(@"failed");
}
// Handle basic authentication challenge if needed
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
NSString *username = @"username";
NSString *password = @"password";
NSURLCredential *credential = [NSURLCredential credentialWithUser:username
password:password
persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
@end
呼び出し
NetWorkToGuiDelegate *nwgd = [[NetWorkToGuiDelegate alloc] init:@selector(login:) :self];
NSString *stringURL = [NSString stringWithFormat:@"%@%@%@%@", dk.baseURL, @"menu?code=",dk.loginCode,@"&v=1"];
NSURL *url = [NSURL URLWithString:stringURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:nwgd];
[urlConnection start];
呼び出しがメインスレッドで発生することを追加します