我想在用户从UIActivityViewController中选择共享活动后,但在显示共享表之前执行上传任务。
具体来说,我需要在活动中使用上传图片的网址。
我已经有了UIActivityItemProvider
的子类,并且我可以在itemForActivityType
方法中进行上传,但是上传代码是基于块的,我无法弄清楚如何让它等待块完成。这甚至可能吗?
这可能是一个简单的编码错误,这是漫长的一天。
我不希望在用户按下共享按钮时上传图像,因为他们可能会取消活动视图,这意味着上传的图像位于没有使用的位置。
这是我目前拥有的代码,但是在图片上传之前它会返回nil,在块中它不会让我返回nil的错误:
- (id) activityViewController:(UIActivityViewController *)activityViewController itemForActivityType:(NSString *)activityType
{
[self getShortUrlForUploadedImageWithCompletionHandler:^(NSString *shortUrl, NSError *error) {
if (!error) {
if ( [activityType isEqualToString:UIActivityTypeMail] ) {
NSString *shareString = @"Email content here using shortUrl";
return shareString;
} else {
return @"";
}
} else {
return @"";
}
}];
return nil;
}
-(void)getShortUrlForUploadedImageWithCompletionHandler:(NSString* (^)(NSString *shortUrl, NSError *error))completionHandler
{
NSData *imageToUpload = UIImageJPEGRepresentation(_image, 75);
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:kShareURL]];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
@"image", @"action",
@"simple", @"format",
nil];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:nil parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData: imageToUpload name:@"image" fileName:@"temp.png" mimeType:@"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *response = [operation responseString];
NSLog(@"response: %@",response);
completionHandler(response, nil);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if([operation.response statusCode] == 403){
NSLog(@"Upload Failed");
return;
}
NSLog(@"error: %@", [operation error]);
completionHandler(nil, error);
}];
[operation start];
}
--------编辑
我真的可以帮忙解决这个问题。我目前的工作是在用户单击“共享”按钮之前,在“活动”选择之前上载图像。所以他们可以取消分享,我留下了冗余上传的图像,或者他们可以选择不需要上传图像的Twitter。 如果选择了电子邮件,我只需要上传图像,我认为我唯一能做的就是在Acticity Provider子类中。
答案 0 :(得分:2)
尝试覆盖UIActivityItemProvider的- (id)activityViewController:(UIActivityViewController *)activityViewController itemForActivityType:(NSString *)activityType
,而不是实现- (id)item
。这个方法将从NSOperation的main方法调用,该方法位于后台线程上。
至于等待网络完成块触发之后,我建议您考虑使用dispatch_semaphore
。这是一个例子:
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"doing some work");
sleep(5);
NSLog(@"done with work");
dispatch_semaphore_signal(semaphore);
});
double delayInSeconds = 60.0;
dispatch_time_t waitTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
NSLog(@"waiting for background thread to finish");
dispatch_semaphore_wait(semaphore, waitTime);
NSLog(@"background thread finished, or took too long");
确保只在后台线程上使用它,否则你将阻止主线程。