AFNetworking3.x Error Code:3840

weixin_33912445發表於2017-06-08

Error: Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

解決辦法:

  • 設定請求管理者,因為傳遞過去和接收回來的資料都不是json型別的,所以在這裡要設定為AFHTTPRequestSerializer和AFHTTPResponseSerializer
manager.requestSerializer = [AFHTTPRequestSerializer serializer];// 請求
manager.responseSerializer = [AFHTTPResponseSerializer serializer];// 響應
  • 在success中將responseObject轉換為一個字串
//轉碼
 NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  • 整體程式碼如下:
 ///AFNetworking 3.x
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];// 請求
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];// 響應
    
    [manager POST:urlString parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
        
        //轉碼
        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

        
        NSLog(@"JSON: %@", string);
        
        
    } failure:^(NSURLSessionTask *operation, NSError *error) {
        
        NSLog(@"Error: %@", error);
        
        
    }];

相關文章