2016-06-07 51 views
0

這裏我使用GET方法從服務器獲取數據,但是當我最小化時,應用程序會在後臺運行,並且在我重新打開後,我看不到這是我以前獲取的任何數據,我只看到數據的第一次,當我最小化,然後重新打開這裏迷路是我的代碼使用「GET」方法獲取數據當我從後臺重新打開應用程序時丟失

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://198.178.4.9:89/mybite_joomla/cron/webapi.php?task=webapi.viewProfile"]cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData 
               timeoutInterval:10 
           ]; 


    [request setHTTPMethod:@"GET"]; 

    [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"]; 

NSError *err; 
NSURLResponse *response; 
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err]; 

NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];{ 


for (NSDictionary *dict in jsonArray) { 

    nameTextView.text =[jsonArray valueForKey:@"name"]; 

    usernameTextView.text =[jsonArray valueForKey : @"username"]; 

    emailTextView.text=[jsonArray valueForKey : @"email"]; 

    cityTextView.text =[jsonArray valueForKey : @"city"]; 

    stateTextView.text =[jsonArray valueForKey : @"state"]; 

    countryTextView.text =[jsonArray valueForKey : @"country"]; 
} 
} 

回答

0

聲明NSDictionary *jsonArray(nonatomic,strong)一個屬性,使用該屬性檢索數據或者填寫textFields。

第二件事,如果你的應用程序在後臺保持很長時間並處於暫停狀態,那麼你應該必須將數據存儲在數據庫中。因爲一旦app被暫停,它就會釋放實例內存。

第二重要的是你不應該使用​​,因爲它是未實現的。

由於Apple documentation狀態,

指定不僅要在本地緩存中的數據被忽略,但代理和其他中間體應指示不顧緩存,只要該協議允許。 該常數未實現,不應使用。

所以,你可以通過0作爲參數傳遞給cachePolicy或可以構造要求,如果timeoutInterval不是強制性等。

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://198.178.4.9:89/mybite_joomla/cron/webapi.php?task=webapi.viewProfile"]]; 
+0

我可以使用存儲NSUserDefaults的會是在我的案件有幫助的數據,如果應用程序仍然在後臺長時間處於暫停狀態得到@Lion – vicky

+0

是的,你可以用'NSUserDefaults' – Lion

+0

並沒有使用的聲明NSDictionary * jsonArray作爲屬性...即使應用程序在後臺進入幾秒鐘我失去了數據@Lion – vicky

相關問題