我有一个代码将图像上传到我的服务器,我在图像上传到服务器时放了一个UIActivityIndicatorView。 它的UIActivityIndicatorView直到代码结束才出现,只有在上传图像后才出现UIActivityIndicatorView。
这是代码:
- (IBAction)sendTHE:(id)sender {
_sendTHE.enabled = NO;
LodingactivityIndicator.hidden = NO;
[LodingactivityIndicator startAnimating];
if ([_textmsg.text isEqualToString:@""]) {
UIAlertView *userExists = [[UIAlertView alloc] initWithTitle:@"Error:" message:@"Please write some message" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[userExists show];
_sendTHE.enabled = YES;
}
else {
NSString *URLString;
NSData *storeData = UIImageJPEGRepresentation(_imageView.image, 90);
if (_imageView.image==NULL)
{ URLString = [NSString stringWithFormat:@"http://37.142.62.22/the/sendmsg.php?f=ns&t=%@&sn=%@&re=%@", _textmsg.text,_userid,_reciverid];
}
else if (_imageView.image!=NULL)
{ URLString = [NSString stringWithFormat:@"http://37.142.62.22/the/sendmsg.php?f=fs&t=%@&sn=%@&re=%@", _textmsg.text,_userid,_reciverid];
}
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[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 *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@.jpg\"\r\n", @"the"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:storeData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
[LodingactivityIndicator stopAnimating];
//NSLog(@"%@",returnString);
//[self performSegueWithIdentifier:@"showfriends" sender:self];
}
}
在NSURLConnection执行请求后启动UIActivityIndicatorView。 如何在请求执行时显示UIActivityIndicatorView?
答案 0 :(得分:1)
您正在主线程上同步执行请求。这意味着在请求返回之前,您的sendTHE:
方法不会返回(并且所有视图都被禁用)。
您有几个选择。
您可以在主线程之外的其他线程上同步执行请求:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
/* Do your networking */
dispatch_async(dispatch_get_main_queue(), ^{
/* Update your UI with the result */
});
});
您可以使用[NSURLConnection +sendAsynchronousRequest:queue:completionHandler:]
。
您可以使用像AFNetworking这样的库来处理这一切。
记住: