2012-03-23 10 views
3

Ich bin derzeit mit diesem Code Daten von einer URL zu erhalten: NSURL *url = [[NSURL alloc] initWithString:urlstring]; NSString *stringfromFB = [[NSString alloc] initWithContentsOfURL:url];Asynchron Abrufen von Daten anstelle von initWithContentsOfURL

Ich habe mich gefragt, wie ich asynchron diese Daten sammeln konnte, so dass meine App jedes Mal nicht einfrieren Ich muß führe dies aus. Vielen Dank!

Antwort

0
// Do not alloc init URL obj. for local use. 
NSString *urlString = @"put your url string here"; 

NSURL *url = [NSURL URLWithString:urlString]; 

NSURLRequest *request = [NSURLRequest requestWithURL:url]; 

[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease]; 


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
- (void)connectionDidFinishLoading:(NSURLConnection *)connection 

Die obigen Delegatmethoden von NSURLConnectionDelegate sind, wo Sie alle Dinge wie Antwortfehler etc behandeln müssen .. Es ist der von einer Standard so können wir direkt sie außer Kraft setzen, ohne

habe ich einmal in meinem Projekt für Asynchron-Anfrage arbeitet es wird aber Wenn Sie Anzahl der empfangenen Bilder auch dann verwenden, auch IconDownloader oder EGOImageView, die das verzögerte Laden von Bildern implementiert und viel geringere Einfriergefahr für die App bietet.

0

Wenn Sie nicht warten möchten, bis eine Verbindung eine URL vollständig geladen hat, können Sie sie asynchron mit NSURLConnection laden.

[NSURLConnection connectionWithRequest: 
    [NSURLRequest requestWithURL: 
    [NSURL URLWithString:yourUrlString]] 
    delegate:self]; 
8

Der einfachste Weg ist in OS 5 wie folgt zur Verfügung:

NSString *stringfromFB; 
NSURL *url = [[NSURL alloc] initWithString:urlstring]; 
NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 
    if (data) { 
     stringfromFB = [[NSString alloc] initWithData:data 
              encoding:NSUTF8StringEncoding]; // note the retain count here. 
    } else { 
     // handle error 
    } 
}]; 

Wenn Sie in os < 5 aus irgendeinem Grund stecken, werden Sie Ihre Verbindung mit einem Delegierten beginnen müssen, und Implementieren Sie das Delegate-Protokoll as illustrated here (und viele andere Stellen).

+0

oben Beispiel fehlt ein] am Ende, aber davon abgesehen ist erstaunlich! Vielen Dank! – ripegooseberry

4

Sie können es mit GCD tun:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ 
    NSURL *url = [[NSURL alloc] initWithString:urlstring]; 
    NSString *stringfromFB = [[NSString alloc] initWithContentsOfURL:url] 
}); 
+0

Macht GCD automatisch Multi-Threading für Sie? Sorry, wenn einfache Frage, ich habe noch keine Erfahrung damit. Vielen Dank! –

+0

Wenn Sie dispatch_async und dispatch_get_global_queue verwenden, YES. Es ist eine Implementierung von TASK PARALELISM, sehr einfach zu bedienen und sehr leistungsfähig (unterstützt Multi-Core). Sie können darüber lesen: http://en.wikipedia.org/wiki/Grand_Central_Dispatch und https://developer.apple.com/library/ios/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html. Ist immer meine erste Wahl für Paralelismus in iOS. – LuisEspinoza

0

Jetzt, da NSURLConnection veraltet ist, müssen Sie NSURLSession verwenden.

NSURLSession *session = [NSURLSession sharedSession]; 

NSURLSessionDataTask *task = [session dataTaskWithRequest: request 
             completionHandler: ^(NSData *data, NSURLResponse *response, NSError *networkError) { 

      NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; 

      if ([httpResponse statusCode] == STATUS_OK) { 
       // use data      
      } 
      else { 
       NSLog(@"Network Session Error: %@", [networkError localizedFailureReason]); 
      } 
}]; 

[task resume];