タイトルに書かれているように、私のCocoaアプリケーションでサーバーからデータをダウンロードするにはどうしたらいいですか? これまで私が探していたのは、thisでした。 iPhoneとMac用のココアのサーバーからデータをダウンロードするにはどうすればいいですか?
1
A
答えて
2
2
あなたが並行して多くのことをダウンロードしていない、あなたは、単純なGETリクエストをやっている場合は、それを行うための最も簡単な方法は、一つに同期リクエストをディスパッチすることですグローバルキューの:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com/"]];
NSURLResponse* response = nil;
NSError* error = nil;
NSData* result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// There will be response data in response now, like the http status code
// etc. You should check this information to make sure you didn't get a 404
// or some other http status error
if(result) {
// you have a good result, do something with it like create a new object or
// pass it to a method on this object, etc.
dispatch_async(dispatch_get_main_queue(), ^{
[self doSomethingWithResponseData:result];
});
} else {
// You got an error making the connection, so handle it
NSLog(@"Error making connection: %@", error);
}
});
**注:このサンプルコードは、GCDを使用していますので、唯一のSnow Leopard(10.6)以上で実行されます。 LeopardまたはTigerをターゲットにする必要がある場合は、ディスパッチされたスレッドセレクタを使用して同じことを実行できますが、インラインでは実行できません。
何が見つかりましたか? – vikingosegundo