【发布时间】:2014-01-16 14:09:10
【问题描述】:
我的班级使用 HTTP Post 向 Twitter 发布推文
这里有一些代码
PostTweet.h
@interface PostTweet : NSObject
- (void)postMyTweet;
@end
PostTweet.m
- (void)postMyTweet
{
accountStore = [[ACAccountStore alloc] init];
accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error)
{
if (granted)
{
allAccounts = [accountStore accountsWithAccountType:accountType];
if ([allAccounts count] > 0)
{
userAccount = [allAccounts objectAtIndex:0];
userName = userAccount.username;
NSURL * reqURL = [NSURL URLWithString:ENDPOINT_MEDIA_UPLOAD];
NSDictionary * parameter = [NSDictionary dictionaryWithObject:tweetTitle forKey:@"status"];
SLRequest *twitterInfoRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodPOST
URL:reqURL
parameters:parameter];
[twitterInfoRequest addMultipartData:tweetImage withName:PARAM_MEDIA type:CONTENT_TYPE_MULTIPART_FORM_DATA filename:nil];
[twitterInfoRequest setAccount:userAccount];
[twitterInfoRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
//show status after done
long result = [urlResponse statusCode];
//Let us say that every thing is ok and I got 200 response
if (result == 200)
{
NSLog(@"%ld",result);
}
}
];
}
}
else
{
NSLog(@"Not authorized");
}
}];
}
在我的viewcontroller.m
- (void) actuallySendTweet
{
PostTweet * pt = [[PostTweet alloc] init];
[pt postTweet];
NSLog(@"Done");
}
问题是:调用testMethod后,如何等待http请求响应,我可以根据响应做任何事情。
现在发生的情况是,只要我调用 testMethod,NSLog 就会立即执行,而不是等待 http 响应。
【问题讨论】:
-
您真的不希望您的主队列等待网络响应。你应该在你的完成块(你有
NSLog(@"%ld", result);)中做任何你想要的推文后操作。实际上,在异步编程中,您应该将请求的启动与服务器响应的处理分开。如果绝对必要,您可以显示一些 UI,告诉用户正在发生背景事情(例如,带有UIActivityViewIndicator的视图),发起请求,并让performRequestWithHandler的完成块将其删除。 -
技术上的答案是“在
performRequestWithHandler中做”,但如果您正在寻找不那么抽象的答案,您必须给我们一个不那么抽象的问题。也就是说,发布这条推文后你到底想做什么?如果您告诉我们您要做什么,我们可能会更容易提出建设性的建议。 -
我只想根据http请求结果显示完成消息。例如如果结果是 200,MBProgressHUD 会弹出成功消息(我知道这部分怎么做)。除 200 以外,将弹出一条失败的消息。 @Rob
-
那么你应该把它放在
performRequestWithHandler的completion块中,而不是在你调用postTweet之后。尽可能简单。并且不要使用已接受答案的障碍调用。
标签: iphone ios objective-c http