2010-06-12 6 views
10

나는이 호출이 stringwithcontentsofurl해야 :시간 제한 stringwithcontentsofurl

[NSString stringWithContentsOfURL:url usedEncoding:nil error:nil]; 

어떻게 간단한 시간 제한이 있음을 줄 수 있습니까? 스레드 또는 작업 대기열 (URL의 내용이 약 100 자임)을 사용하고 싶지 않습니다. 연결이 느릴 때 너무 오래 기다리 길 원치 않습니다.

답변

9

이 경우 NSURLConnection 클래스 메서드 +sendSynchronousRequest:returningResponse:error:을 사용하는 것이 가장 좋을 수 있습니다. 문자열을 초기화 할 수있는 데이터 객체를 반환합니다 (-initWithData:encoding: 사용). 해당 -initWithURL:cachePolicy:timeoutInterval: 메소드를 사용하여 NSURLRequest을 생성 한 다음 해당 요청을 +sendSynchronousRequest:returningResponse:error:의 첫 번째 매개 변수로 전달하여 시간 초과를 지정할 수 있습니다.

+0

대!, 즉 불과했다! 감사! – sergiobuj

+1

유일한 문제는 '+ stringWithContentsOfURL : usedEncoding : error :'로하는 인코딩의 내장 된 추측을 얻지 못하기 때문에 스스로 롤백해야한다는 것입니다. –

17

는 여기에 내 걸릴이다 : 나는 그것을 상상으로

NSString* link = @"http://example.com"; 
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:link] cachePolicy:0 timeoutInterval:5]; 
NSURLResponse* response=nil; 
NSError* error=nil; 
NSData* data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
NSString* stringFromServer = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]; 
+1

굉장! 작품 100 % –