2016-09-08 3 views
0

Когда я получил ответ своего сервера и попытался сохранить его в plist, но файл plist не создается.Plist не создается в Objective C

Я вошел путь к файлу и словарные содержимое, но все они имеют данные по-прежнему Plist не создавая

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 
    [self sideMenu:@"ML"]; 

    return YES; 
} 

это будет вызывать следующий метод

-(void)sideMenu:(NSString *)title{ 

    NSString *myRequestString = [[NSString alloc] initWithFormat:@"data=%@&deviceid=e8ef8c98262185ec",title]; 

    NSData *myRequestData = [NSData dataWithBytes:[myRequestString UTF8String ] length: [ myRequestString length ] ]; 

    NSMutableURLRequest *request = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString:SIDE_MENU]]; 
    [request setHTTPMethod:@"POST"]; 
    [request setHTTPBody: myRequestData]; 
    NSURLResponse *response; 
    NSError *err; 
    NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse:&response error:&err]; 
    NSString* responseString = [[NSString alloc] initWithData:returnData encoding:NSNonLossyASCIIStringEncoding]; 
    NSArray *myArray = [responseString componentsSeparatedByString:@"<!DOC"]; 
    //NSLog(@"%@",myArray); 
    if (myArray != nil || [myArray count] > 0) { 
     NSData *data = [[[myArray objectAtIndex:0]stringByReplacingOccurrencesOfString:@"\n" withString:@""] dataUsingEncoding:NSUTF8StringEncoding]; 
     id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 
     [self sideMenuFile:title :json]; 
    } 



} 




-(NSString *)sideMenuFile:(NSString *)titleName :(NSDictionary *)dict{ 
    NSString *filePath; 
    MyManager *sharedManager =[MyManager sharedManager]; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    if([titleName isEqualToString:@"ML"]) 
    { sharedManager.sideMenu = [[NSDictionary alloc]init]; 
     sharedManager.sideMenu = dict; 
     filePath = [documentsDirectory stringByAppendingPathComponent:@"ML.plist"]; 
    }else if ([titleName isEqualToString:@"HM"]){ 
     filePath = [documentsDirectory stringByAppendingPathComponent:@"HM.plist"]; 

    }else if ([titleName isEqualToString:@"PDC"]){ 
     filePath = [documentsDirectory stringByAppendingPathComponent:@"PDC.plist"]; 

    }else if ([titleName isEqualToString:@"SM"]){ 
     filePath = [documentsDirectory stringByAppendingPathComponent:@"SM.plist"]; 

    }else if ([titleName isEqualToString:@"GL"]){ 
     filePath = [documentsDirectory stringByAppendingPathComponent:@"GL.plist"]; 

    }else if ([titleName isEqualToString:@"CU"]){ 
     filePath = [documentsDirectory stringByAppendingPathComponent:@"CU.plist"]; 

    }else if ([titleName isEqualToString:@"BR"]){ 
     filePath = [documentsDirectory stringByAppendingPathComponent:@"GL.plist"]; 

    } 

    NSLog(@"%@",filePath); //printing path 
    [dict writeToFile:filePath atomically:YES]; 

    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil; 

    NSString *plistName = @"GL"; 
    NSString *finalPath = [basePath stringByAppendingPathComponent: 
          [NSString stringWithFormat: @"%@.plist", plistName]]; 

    NSDictionary *dictww=[[NSDictionary alloc]initWithContentsOfFile:finalPath]; 




    NSLog(@"dict%@",dictww); //printing nill 


    return filePath; 
} 

структура JSON файл

{ 
    sigallery =  { 
     rows =   (
         { 
       active = True; 
       gallerytext = "<null>"; 
       galleryurl = "assets/img/content-images/1.jpg"; 
       moddt = "2016-07-19T12:28:18.873"; 
       onclickurl = "testd.in"; 
       settingsid = 1; 
       showfromdt = "1901-01-01T00:00:00.0"; 
       showsequence = 1; 
       showuptodt = "2099-12-31T00:00:00.0"; 
       videoimagebanneraudioswitch = I; 
      }, 
         { 
       active = True; 
       gallerytext = "<null>"; 
       galleryurl = "assets/img/content-images/2.jpg"; 
       moddt = "2016-07-19T12:28:18.873"; 
       onclickurl = "testd.in"; 
       settingsid = 1; 
       showfromdt = "1901-01-01T00:00:00.0"; 
       showsequence = 2; 
       showuptodt = "2099-12-31T00:00:00.0"; 
       videoimagebanneraudioswitch = I; 
      } 
      ) 
      } 
      } 
+0

Refer - http://stackoverflow.com/questions/12170871/how-to-add-a-key-value-pair-to-a-plist-file-in-objective-c и http: // stackoverflow .com/questions/23867337/how-can-i-save-retrieve-delete-update-my-data-in-plist-file-in-ios – Signare

+0

'[finalPath isEqualToString: filePath]'? Объявление/Именование вашего метода 'sideMenuFile: noTextHere:' явно НЕ рекомендуется. – Larme

ответ

0

Ваш код делает ряд неоптимальных предположений.

1)

Всякий раз, когда вы выписывать файл, вы всегда должны проверить для любого состояния ошибки, если она доступна. writeTo... методы NSDictionary СДЕЛАЕМ возвращают булевы ли файл был выписан или нет, так что вы можете сделать:

NSLog(@"%@",filePath); //printing path 
BOOL success = [dict writeToFile:filePath atomically:YES]; 
if (success == false) 
{ 
    NSLog(@"did not successfully write dictionary to path %@", filePath); 
} else { 
    // ... do everything else in here 
} 

2)

Вы выписывать файлы Жека формата titleName + GL | PDC | SM.plist но при попытке прочитать вещи назад, нет titleName как часть finalPath, поэтому здесь ничего не выстраивается.

3)

Кроме того, почему вы предполагаете basePath правомочно (похоже, это может быть ноль)?

Смежные вопросы