我已經使用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