我需要将图像上传到网络服务。下面是我返回上传图片的代码片段。图像尺寸非常大(大约 6Mb)。我正在使用 GCD 在后台线程中上传该图像。
if([VSCore ConnectedToInternet ])
{
bgTask = [[UIApplication sharedApplication]beginBackgroundTaskWithExpirationHandler: ^{
dispatch_async(dispatch_get_main_queue(), ^{
//[application endBackgroundTask:self->bgTask];
//self->bgTask = UIBackgroundTaskInvalid;
});
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[vrs write:data toURI:URI];
[[UIApplication sharedApplication]endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
});
//
}
-(BOOL)write:(NSData *)data toURI:(NSString *)URI
{
BOOL retVal = NO;
NSString* requestDataLengthString = [[NSString alloc] initWithFormat:@"%d", [data length]];
NSRange range = [URI rangeOfString:@"http"];//Is http?
if(range.location != NSNotFound)
{
//Yes, http
NSMutableURLRequest *httpRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:URI]];
[httpRequest setHTTPMethod:@"POST"];
[httpRequest setHTTPBody:data];
[httpRequest setValue:@"application/xml" forHTTPHeaderField:@"Content-Type"];
[httpRequest setValue:requestDataLengthString forHTTPHeaderField:@"Content-Length"];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:httpRequest delegate:self];
[theConnection release];
[httpRequest release];
if (theConnection)
{
receivedData=[[NSMutableData data] retain];
retVal = YES;
}
else
{
NSError *error = [NSError alloc];
NSLog(@"Connection failed! Error - %@ %@",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
[error release];
retVal = NO;
}
}
return retVal;
}
现在我面临的问题是,如果我尝试在后台线程中上传图像,则请求不会发送到服务器(我正在检查服务器上的日志文件)。但是如果我在主线程中上传图像,则请求将发送到服务器(仅出于测试目的,我知道在主线程中上传大图像不是一个好主意)。那么我在这里做错了什么?后台线程有什么问题吗?请帮帮我。提前致谢。