我有两个视图:myFristView和mySecondView,在 myFristView 我有一个代码可以读取我的数据库中的字段,然后发送到 PHP 服务器,这个代码NSInvocationOperation使用这个类在后台模式下发送文件。
向服务器发送文件的过程有点慢(因为数据库中有很多记录),您经常被迫等待所有发送的文件才能进入 mySecondView,这是因为除了我使用 ARC之外,之前的视图停止工作,应用程序专注于第二个视图,停止发送文件。
所以我想找到一种方法:当我离开屏幕(myFristView)时,应用程序继续运行将文件发送到 PHP 服务器的命令。
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(sendFiles) object:nil];
[queue addOperation:operation];
-(void)sendFiles{
......
NSString *urlString = @"http://www.website.com/receiveFiles.php";
NSString *filename = @"fazerbem.sqlite";
request= [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@.jpg\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:YOUR_NSDATA_HERE]];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"%@", returnString);
}