Facebook SLRequest搞乱了NSURLConnection

时间:2013-10-28 03:15:24

标签: ios objective-c nsurlconnection social-framework slrequest

我正在尝试使用SLRequest iOS API获取Facebook数据,这似乎工作正常 -

NSDictionary *parameters = @{};
NSURL *feedURL = [NSURL URLWithString:@"https://graph.facebook.com/me/home"];

SLRequest *feedRequest = [SLRequest 
    requestForServiceType:SLServiceTypeFacebook
    requestMethod:SLRequestMethodGET
    URL:feedURL 
    parameters:parameters];

feedRequest.account = facebookAccount;

[feedRequest performRequestWithHandler:^(NSData *responseData, 
       NSHTTPURLResponse *urlResponse, NSError *error)
{
    // something
}];

然而,在此之后,我向我的一台服务器发出HTTP POST请求,

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    NSData *requestData = [NSData dataWithBytes:[jsonData bytes] length:[jsonData length]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody: requestData];
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];

使数据正常(从服务器日志验证),但我没有得到任何HTTP响应

connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response

过去在没有SLRequest POST的情况下工作正常,我能够对该部分进行评论并重新开始工作。

我在这里缺少什么?

2 个答案:

答案 0 :(得分:2)

你如何创建一个强大的NSURLConnection引用,我猜iOS正在释放该对象,这就是为什么你的委托永远不会被调用。

所以,而不是:

NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];

使用:

self.connection=[[NSURLConnection alloc]initWithRequest:request delegate:self];

其中:

@property(nonatomic, strong)NSURLConnection * connection;

让我知道它是怎么回事,干杯。

亲切的问候

答案 1 :(得分:1)

对我有用的修复不是使用SLRequest块加载,而是在第一个时刻使用NSURLConnection和适当的NSURLConnectionDelegate方法。第二次使用此委托时,加载应该没问题,请尝试将所有加载保存在同一个实用程序类中,以便它们共享同一个委托。对我而言,这是twitters v1.1 API的问题。

所以在你的代码中尝试删除块,然后你需要准备SLRequest:

urlData=[[NSData alloc] init];
// change that SLRequest to a NSURLRequest
NSURLRequest *request = [feedRequest preparedURLRequest];
dispatch_async(dispatch_get_main_queue(), ^{
    [NSURLConnection connectionWithRequest:request delegate:self];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
});

然后使用NSURLConnectionDelegate方法,捕获加载的NSData:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    connection=nil;
    NSError *jsonParsingError = nil;
    NSMutableDictionary *deserializedData  = [NSJSONSerialization JSONObjectWithData:urlData options:NSJSONReadingAllowFragments error:&jsonParsingError];
    if (deserializedData) {
         // handle the loaded dictionary as you please
    } 
}

这个修正案的灵感来自Keith Harrison的帖子:http://useyourloaf.com/blog/2013/06/24/migrating-to-the-new-twitter-search-api.html

所以也归功于他。