2014-08-29 65 views
1

我用下面的代碼來設置我的業務經理標題:AFHTTPRequestOperationManager的行動沒有得到

requestSerializerJson = [AFJSONRequestSerializer serializer]; 
[requestSerializerJson setValue:[taskHandler getBranchesApiConstantForName:@"header_value_content_type"] forHTTPHeaderField:[taskHandler getBranchesApiConstantForName:@"header_name_content_type"]]; 
[requestSerializerJson setValue:[taskHandler getBranchesApiConstantForName:@"header_value_api_key"] forHTTPHeaderField:[taskHandler getBranchesApiConstantForName:@"header_name_api_key"]]; 

httpRequestOperationManager = [AFHTTPRequestOperationManager manager]; 
httpRequestOperationManager.requestSerializer = requestSerializerJson; 
httpRequestOperationManager.responseSerializer = [AFJSONResponseSerializer serializer]; 
httpRequestOperationManager.operationQueue = [[NSOperationQueue alloc] init]; 
httpRequestOperationManager.operationQueue.maxConcurrentOperationCount = 1; 

然後,我有下載多個JSON字符串的方法:

- (void)downloadBranches { 

    NSLog(@"Test %@", httpRequestOperationManager.requestSerializer.HTTPMethodsEncodingParametersInURI); 

    for (NSString *branchUuid in taskHandler.addedBranchesUuids) { 

     NSString *urlString = [NSString stringWithFormat:@"%@%@%@", urlBase, [taskHandler getBranchesApiConstantForName:@"getbranch_suffix"], branchUuid]; 
     NSURL *URL = [NSURL URLWithString:urlString]; 
     NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 

     NSLog(@"Test %@", request.allHTTPHeaderFields); 

     AFHTTPRequestOperation *op = [httpRequestOperationManager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) { 

      NSLog(@"JSON: %@", responseObject); 

     } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 

      NSLog(@"Error: %@", error); 
     }]; 
     op.responseSerializer = [AFJSONResponseSerializer serializer]; 

     [httpRequestOperationManager.operationQueue addOperation:op]; 
    } 
} 

所有的操作都被執行,但是我從服務器收到一條消息,說我沒有提供身份驗證密鑰。

我特別將其設置在第3行 - 對於requestSerializerJson,然後將其添加到httpRequestOperationManager,因此所有請求都應使用標頭。

我添加了一個NSLog來打印request.allHTTPHeaderFields,但它說「(null)」。

我該如何解決這個問題?

回答

1

downloadBranches通過手動構建NSURLRequest完全繞過了串行器。序列化程序的要點就是爲你做到這一點。

您需要在您的串行器上調用requestWithMethod:URLString:parameters:,它會返回一個NSURLRequest與您想要的標題。

或者只是在for循環內使用操作管理器的GET:…方法;你的用例看起來並不需要這些其他的東西。

+0

感謝您的澄清 - 我錯了。但是,還有一個問題:當我使用AFHTTPSessionManager及其GET方法時,似乎沒有辦法確保所有請求都按順序執行。 AFHTTPRequestOperationManager上的GET具有相同的效果,還是僅僅創建一個請求操作,然後我可以將它添加到操作隊列中? – JakeP 2014-09-01 08:41:48

+0

GET方法和當前代碼都沒有強制執行一次正在運行的操作。 – 2014-09-01 14:25:53

+0

您可以將操作隊列的最大併發操作屬性設置爲1;那麼要麼完成這一點。或者,您可以在獲取所需數據的操作的完成處理程序中安排依賴操作。 – 2014-09-01 14:28:52