我已经使用Mac OS X Reference Library中Using NSURLConnection中的指导原则安装了一个NSURLConnection,创建一个NSMutableURLRequest作为POST到一个带有自定义主体的PHP脚本的POST以上传20 MB数据(请参见下面的代码)。请注意,帖子主体是什么(换行符和全部)与完全匹配现有的桌面实现。为什么我的NSURLConnection如此缓慢?
当我在iPhone模拟器中运行这个功能时,这个帖子是成功的,但比我在Mac上用C++在本地运行等效代码要长一个数量级(分别为20分钟和20秒)。
任何想法为什么差异如此戏剧性?我明白模拟器会给出与实际设备不同的结果,但我预计至少会有类似的结果。
感谢
const NSUInteger kDataSizePOST = 20971520;
const NSString* kUploadURL = @"http://WWW.SOMEURL.COM/php/test/upload.php";
const NSString* kUploadFilename = @"test.data";
const NSString* kUsername = @"testuser";
const NSString* kHostname = @"testhost";
srandom(time(NULL));
NSMutableData *uniqueData = [[NSMutableData alloc] initWithCapacity:kDataSizePOST];
for (unsigned int i = 0 ; i < kDataSizePOST ; ++i) {
u_int32_t randomByte = ((random() % 95) + 32);
[uniqueData appendBytes:(void*)&randomByte length:1];
}
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:kUploadURL]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"aBcDd";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:@"--%@\nContent-Size:%d",boundary,[uniqueData length]] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"\nContent-Disposition: form-data; name=test; filename=%@", kUploadFilename] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithString:@";\nContent-Type: multipart/mixed;\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:uniqueData]];
[postbody appendData:[[NSString stringWithFormat:@"--%@\nContent-Size:%d",boundary,[kUsername length]] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"\nContent-Disposition: inline; name=Username;\n\r\n%@",kUsername] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"--%@\nContent-Size:%d",boundary,[kHostname length]] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"\nContent-Disposition: inline; name=Hostname;\n\r\n%@",kHostname] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"\n--%@--",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
_receivedData = [[NSMutableData data] retain];
} else {
// Inform the user that the connection failed.
}
[request release];
[uniqueData release];
首先,使用profiler运行您的代码。 – Max 2011-02-09 15:39:42