我正在开发iOS 4.x设备的应用程序。我正在实现一个通信模块,其中in-in程序定期向服务器发送文件(有时一次多个文件)。我正在使用以下函数实现代码。我想知道,Apple的http代码如下支持“异步”方法(或)我是否必须使用某些第三方API,如“ASIHTTPRequest”来支持我的函数中的异步调用。请指教。
-(void) HttpUpload : (UIImage *) image :(NSString *) fileNameStr
{
NSData *imageData = UIImageJPEGRepresentation (image, 90);
NSString *urlString = @"http://iphone.zcentric.com/test-upload.php";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
// header now..
NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
// Create body of the post..
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@.jpg\"\r\n", fileNameStr] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
// lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(responseString);
}
谢谢!
答案 0 :(得分:3)
使用[[NSURLConnection alloc] initWithRequest:request delegate:self];
然后实现委托方法。
修改强> 尝试在代码中更改此内容 删除这些行
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
在此处添加
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self]; //Warning. this is a leak. You have to use a propery so you can properly release later.
添加这些代表:
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
//Handle the error
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
//If you need to handle partial data do that here
//This method can be called several times. So, may be you have to append the data in an NSMutableData object
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
//If you need to handle the response do that here
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
//This callback is the last one
}