문제

5 개의 문자열이있는 텍스트 파일이 있습니다.nsurlconnection을 사용 하여이 파일의 수분을 얻을 필요가 있습니다.그러나 nslog는 나를 보여줍니다. '덤프'가 비어 있습니다.NSMutableData에서 NSArray로 데이터를 어떻게 변환 할 수 있습니까?배열은 테이블보기에서 5 항목을 보여줄 필요가 있기 때문입니다.

NSURLRequest *theRequest=[NSURLRequest
                         requestWithURL:[NSURL URLWithString:@"http://dl.dropbox.com/u/25105800/names.txt"]
                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                         timeoutInterval:60.0];

NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
    receivedData = [NSMutableData data];
    NSString *dump = [[NSString alloc] initWithData:receivedData
                         encoding:NSUTF8StringEncoding];
    NSLog(@"data: %@", dump);
    NSArray *outputArray=[dump componentsSeparatedByString:@"\n"];
    self.namesArray = outputArray;
.

미리 감사드립니다.BTW URL 작동, 파일을 볼 수 있습니다.

도움이 되었습니까?

해결책

대리자를 사용하지 않으려면 다음과 같이 NSURLConnection으로 동기 호출을 사용할 수 있습니다.

NSURLRequest *theRequest=[NSURLRequest
                     requestWithURL:[NSURL URLWithString:@"http://dl.dropbox.com/u/25105800/names.txt"]
                     cachePolicy:NSURLRequestUseProtocolCachePolicy
                     timeoutInterval:60.0];

NSError *error = nil;
NSHTTPURLResponse *response = nil;
NSData *receivedData = [NSURLConnection sendSynchronousRequest:theRequest response:&response error:&error];

if (error == nil) {
    NSString *dump = [[NSString alloc] initWithData:receivedData
                     encoding:NSUTF8StringEncoding];
    NSLog(@"data: %@", dump);
    NSArray *outputArray=[dump componentsSeparatedByString:@"\n"];
    self.namesArray = outputArray;
}
.

이 비동기 적으로 실행되지 않습니다.메인 스레드에서 실행되도록하려면 주 스레드 / UI를 차단하려면 별도의 스레드를 사용하여 해당 코드를 실행하거나 GCD를 사용하십시오.

다른 팁

이 솔루션을 대리인으로 구현하는 방법은 다음과 같습니다. .h 파일의

:

@interface MyClass : NSObject <NSURLConnectionDelegate, NSURLConnectionDataDelegate>

@property (nonatomic, retain) NSMutableData *receivedData;
@property (nonatomic, retain) NSArray *namesArray;

@end
.

.m 파일 :

@implementation MyClass

@synthesize receivedData = _receivedData;
@synthesize namesArray = _namesArray;

- (id)init {
    self = [super init];
    if (self) {
        self.receivedData = [NSMutableData data];
        NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://dl.dropbox.com/u/25105800/names.txt"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
        NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
        [connection start];

    }
    return self;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSLog(@"Received response! %@", response);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.receivedData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSString *dump = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding];
    NSLog(@"data: %@", dump);
    self.namesArray = [dump componentsSeparatedByString:@"\n"];
}

@end
.

대리인을 사용하여 수신 된 데이터를 relevenionedData (물론 바로 바로 빼앗아냅니다.) 귀하가 예제에서 그랬던 것처럼 데이터를 문자열로 변환합니다....에NSURLConnectionDelegate 를 살펴보십시오

NSURLConnection의 대리자 메서드를 들어오는 데이터에 통지 받아야합니다.비동기 메소드를 사용하고 있습니다.

또한 [NSMutableData data]는 빈 데이터 객체를 만듭니다. 그래서 데이터를 포함 할 것으로 기대할 수 없습니다 ..

https://developer.apple.com/library/ios/#documentation/cocoa/conceptual/urlloadingsystem/tasks/usingnsurlconnection.html#/apple_ref/doc/uid/20001836-bajeiee (완전히!)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top