當我異步使用NSURLConnection
嘗試獲取帶有圖像數據的NSData
時,圖像將返回爲空白,但當我同步使用dataWithContentsOfURL
時,我沒有問題,圖像數據正確。是否有任何理由爲什麼我的異步方法會失敗?使用NSURLConnection時圖像空白但使用dataWithContentsOfURL時不使用
這工作:
NSData *data = [NSData dataWithContentsOfURL: url];
NSLog(@"TEST %@", data);
UIImage *map = [UIImage imageWithData:data];
mapView.image = map;
這並不:
//
// MapHttpRequest.m
// GTWeb
//
// Created by Graphic Technologies on 6/21/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "MapHttpRequest.h"
@implementation MapHttpRequest
@synthesize receivedData;
@synthesize dataString;
@synthesize vc;
- (void)request:(NSString *)url fromView:(UIViewController *) theVC
{
vc = theVC;
// Create the request.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSLog(@"URL: %@", url);
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere.
receivedData = [[NSMutableData data] retain];
} else {
// Inform the user that the connection failed.
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// This method is called when the server has determined that it
// has enough information to create the NSURLResponse.
// It can be called multiple times, for example in the case of a
// redirect, so each time we reset the data.
// receivedData is an instance variable declared elsewhere.
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.
// receivedData is an instance variable declared elsewhere.
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// release the connection, and the data object
[connection release];
// receivedData is declared as a method instance elsewhere
[receivedData release];
// inform the user
NSLog(@"Connection failed! Error - %@ %@",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// do something with the data
// receivedData is declared as a method instance elsewhere
[vc mapImageConnectionFinished:receivedData];
// release the connection, and the data object
[dataString release];
[connection release];
[receivedData release];
}
@end
這將有助於查看您使用NSURLConnection的代碼。 – highlycaffeinated
@highlycaffeinated我已經編輯過它,我不小心打進了,並在我準備好之前貼出來。 – Millec8
我看不到你在哪裏填充你創建的receivedData對象。 – highlycaffeinated