2014-03-02 53 views
-1

您好我正在研究iOS中的簡單激活應用程序。我想保存的UDID在文本文件中,平等的文本文件與當前的UDID,但我不能保存UDID到文本文件將udid字符串保存到文本文件

NSString *udid = [[[UIDevice currentDevice] identifierForVendor] UUIDString]; 

NSURL *fileURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"h" ofType:@"txt"]]; 

NSMutableString *text = [NSMutableString stringWithContentsOfURL:fileURL encoding:NSUTF8StringEncoding error:nil]; 

NSLog(@"text is : %@",text); 

NSString *text1 = text; 

NSString *y; 

if ([text1 isEqualToString:y]) { 

    [text appendString:udid]; 

    NSString *myURLString = [fileURL absoluteString]; 

    [text writeToFile:myURLString atomically: YES encoding:NSUTF8StringEncoding error:nil]; 

    NSLog(@"saved to file : %@",text); 

}else { 

    if ([text isEqualToString:udid]) { 

     NSLog(@"yes thats it"); 
     lable.text = @"yes thats it"; 

    }else { 
     NSLog(@"nononono"); 
     exit(0); 


    } 
} 

回答

0

有你的代碼的幾個問題。開始於:

if ([text1 isEqualToString:y]) { 

其中是「y」定義或聲明?

另外,在寫入文件時,您從不查看錯誤參數。更改此:

[text writeToFile:myURLString atomically: YES encoding:NSUTF8StringEncoding error:nil]; 

這樣:

NSError *error; 

BOOL success = [text writeToFile:myURLString atomically: YES encoding:NSUTF8StringEncoding error:&error]; 

if(NO == success) 
{ 
    NSLog(@"error from writing to %@ is %@", myURLString, [error localizedDescription]); 
} 

至於你正在運行成什麼樣的錯誤,你可能有一個更好的線索。

最後,通過您的評論,您已經明確表示您正在嘗試將文件直接寫入應用程序包中。這是一個很大的(沙箱)不,不。

相反的:

NSURL *fileURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"h" ofType:@"txt"]]; 

做到這一點,而不是:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *basePath = [paths firstObject]; 
NSURL *fileURL = [NSURL fileURLWithPath:[basePath stringByAppendingString:@"/h.txt"]]; 

,這將您的文件保存到文件目錄,這是一個合法的地方保存文件。

+0

它給我:寫入文件時出錯:///Users/mji/Library/Application%20Support/iPhone%20Simulator/7.0-64/Applications/C48463FB-F7F0-47AD-A40A-958A3583C29E/active%20text。 app/h.txt是操作無法完成。 (可可錯誤4.) – user3001228

+0

你不應該試圖寫入應用程序的包,這是不允許的。 –

+0

現在它給了我這個當我想保存udid文件寫入文件錯誤:///Users/mji/Library/Application%20Support/iPhone%20Simulator/7.0-64/Applications/C48463FB-F7F0-47AD-A40A -958A3583C29E/Documents/h.txt爲(null) – user3001228

相關問題