我在一個名爲WebServices的類中實現了一個RESTful API。我從我的應用程序中的其他類調用此類中的方法,並希望在成功完成Web服務時執行操作。我有一個完成塊作爲我的方法頭文件的一部分,但我不確定是否正確使用它們,因爲應用程序似乎無法到達方法調用的完成部分。這是我打電話我的方法:Web服務完成後的完成塊?
[services callUnregisterForPushNotifications:savedAccessToken pushToken:savedPushToken completionBlock:^(NSMutableArray *resultsArray) {
NSLog(@">>> COMPLETE! <<<");
[self.loadingView removeFromSuperview];
}];
而且方法我打電話看起來像這樣:
- (void)callUnregisterForPushNotifications:(NSString *)accessToken
pushToken:(NSString *)pushToken
completionBlock:(void (^)(NSMutableArray *resultsArray))completion{
NSLog(@"UNREGISTER FOR PUSH CALLED!");
NSLog(@"PUSH TOKEN %@", pushToken);
NSString *appendUrl = @"alerts/unregisterpush/";
NSLog(@"APPEND URL %@",appendUrl);
NSURL *unregisterUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@", BaseURLString, appendUrl]];
NSLog(@"UNREGISTER URL: %@",unregisterUrl);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:unregisterUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
[request setHTTPMethod:@"PUT"];
NSString *appendToken = [NSString stringWithFormat:@"Bearer %@", accessToken];
NSLog(@"TOKEN: %@",appendToken);
[request addValue:appendToken forHTTPHeaderField:@"Authorization"];
[request addValue:@"application/json, text/plain, */*" forHTTPHeaderField:@"Accept"];
[request addValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
NSString *postString = [NSString stringWithFormat:@"{\"Guid\":\"%@\"}",pushToken];
NSLog(@"POST STRING: %@",postString);
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"REQUEST %@",request);
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(@"UNREGISTER PUSH NOTIFICATIONS RESPONSE: %@", response);
NSLog(@"UNREGISTER PUSH NOTIFICATIONS ERROR: %@", error);
NSLog(@"UNREGISTER PUSH NOTIFICATIONS DATA: %@", data);
NSData *_data = data;// ... whatever
NSMutableString *_string = [NSMutableString stringWithString:@""];
for (int i = 0; i < _data.length; i++) {
unsigned char _byte;
[_data getBytes:&_byte range:NSMakeRange(i, 1)];
if (_byte >= 32 && _byte < 127) {
[_string appendFormat:@"%c", _byte];
} else {
[_string appendFormat:@"[%d]", _byte];
}
}
NSLog(@"UNREGISTER PUSH RESPONSE: %@", _string);
id obj= [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (!obj) {
//NSLog(@"REGISTER PUSH NOTIFICATIONS ERROR: %@", error);
} else {
//NSLog(@"REGISTER PUSH NOTIFICATIONS DATA: %@", obj);
//self.accessToken = [obj valueForKey:@"access_token"];
//NSLog(@"ACCESS TOKEN: %@",self.accessToken);
}
}];
}
任何意見/輸入,將不勝感激,在此先感謝!
哪部分沒被調用?它不會執行「註銷被觸發!」塊,還是不做「>>> COMPLETE!<<<」塊,還是它不做? – Stonz2
請注意,NSURLConnection已被棄用。您應該轉而使用NSURLSession。 – Joride