2015-06-28 59 views
2

我試圖顯示進度欄,因爲我從url下載JSON。 JSON正確下載,但我不知道如何顯示進度欄。我嘗試過使用UIProgressView,但它不顯示在屏幕上。任何建議,將不勝感激。如何使用AFNetworking AFHTTPRequestOperationManager顯示ProgressBar

CGFloat width = [UIScreen mainScreen].bounds.size.width; 
CGFloat height = [UIScreen mainScreen].bounds.size.height; 

CGRect rect = CGRectMake(width/2, height/2, width/5, height/5); 
UIProgressView *myProgressView = [[UIProgressView alloc]initWithFrame:rect]; 
myProgressView.progressViewStyle = UIProgressViewStyleBar; 
[self.view addSubview:myProgressView]; 

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];  
[manager GET:@"https:urlWithJson" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) { 
     [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) 
     { 
      myProgressView.progress = (float)totalBytesRead/totalBytesExpectedToRead; 
     }]; 
     [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
      NSLog(@"operation Completed"); 
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
      NSLog(@"ERROR"); 
     }]; 

     [operation start]; 
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
     NSLog(@"timeout Error: %@", error); 
    }]; 
+0

totalBytesExpectedToRead是否有值? HTTP頭必須包含文檔的大小才能獲得預期的總字節數。 – Thomas

+0

我嘗試在setDownloadProgressBlock裏放入一個NSLog語句,但它沒有打印任何東西。有沒有更好的辦法可以實現我想要的? – baskInEminence

回答

5

您設定的成功塊,這是一個有點太晚了裏面的下載進度塊;)

試試這個:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];  
AFHTTPRequestOperation *operation = [manager GET:@"https:urlWithJson" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) { 
    NSLog(@"Complete"); 
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    NSLog(@"Error: %@", error); 
}]; 

[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) { 
    myProgressView.progress = (float)totalBytesRead/totalBytesExpectedToRead; 
}]; 
2

簡單的解決方案爲斯威夫特:

let progress: UIProgressView? //for example, reference to IBOutlet 
let manager = AFHTTPRequestOperationManager() 
let operation = manager.POST(query, parameters: parameters, constructingBodyWithBlock: { multipartData in 

      //do sth with your multipartData 
    }, success: { operation, response in 

      //success 
    }) { operation, error in 

      //failure 
} 

progress?.setProgressWithUploadProgressOfOperation(operation!, animated: true) 

你什麼都不做。這足以顯示你的觀點。

相關問題