简体   繁体   English

数据未写入iOS中的文件

[英]Data not writing to the file in iOS

NSData is not writing to the file, below is my code: NSData没有写入文件,下面是我的代码:

 NSURL *myUrl=[NSURL URLWithString:@"http://192.168.2.8:70/sampledata.xls"];
 NSURLRequest *myRequest=[NSURLRequest requestWithURL:myUrl];
 myData=[[NSMutableData alloc]initWithLength:0];
 NSURLConnection *myConnection=[[NSURLConnection alloc]initWithRequest:myRequest delegate:self startImmediately:YES];

 NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory=[paths objectAtIndex:0];
NSString *str=[documentDirectory stringByAppendingPathComponent:@"samplefile.xls"];
[myData writeToFile:filename atomically:YES];




BOOL fileExists=[[NSFileManager defaultManager]fileExistsAtPath:str];
NSLog(@"File ----%d",fileExists);

can anyone point me where i am doing wrong? 谁能指出我做错了什么?

Change 更改

NSString *filename=[NSString stringWithFormat:@"%@samplefile.xls",documentDirectory];

to

NSString *path=[documentsDirectory stringByAppendingPathComponent:@"samplefile.xls"];

Let me know it is working or not!!! 让我知道它是否有效!!!

Happy Coding!!! 快乐编码!

You are requesting the data asynchronously and when you are writing data to your file it's length is 0 您正在异步请求数据,并且在将数据写入文件时,其长度为0

What you need to do? 你需要做什么?

Implement the NSURLConnectionDelegate methods and receive the data there. 实现NSURLConnectionDelegate方法并在那里接收数据。 After finishing the connection save the data to the file: 连接完成后,将数据保存到文件中:

#pragma mark NSURLConnection Delegate Methods


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    // A response has been received, this is where we initialize the instance var you created
    // so that we can append data to it in the didReceiveData method
    // Furthermore, this method is called each time there is a redirect so reinitializing it
    // also serves to clear it
    myData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Append the new data to the instance variable you declared
    [myData appendData:data];
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                  willCacheResponse:(NSCachedURLResponse*)cachedResponse {
    // Return nil to indicate not necessary to store a cached response for this connection 
    return nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // The request is complete and data has been received
    // You can parse the stuff in your instance variable now
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    NSString *fileName = [documentDirectory stringByAppendingPathComponent:@"samplefile.xls"];
    [myData writeToFile:fileName atomically:YES];
    BOOL fileExists = [[NSFileManager defaultManager]fileExistsAtPath:str];
    NSLog(@"File ----%d",fileExists);
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // The request has failed for some reason!
    // Check the error var
}

Code taken from : http://codewithchris.com/tutorial-how-to-use-ios-nsurlconnection-by-example/ 代码取自: http : //codewithchris.com/tutorial-how-to-use-ios-nsurlconnection-by-example/

You lost a "/" in your format. 您以格式丢失了“ /”。 It must be: @"%@/samplefile.xls" 它必须是:@“%@ / samplefile.xls”

问题是在"samplefile.xls"您必须将文件扩展名更改为.txt.csv ,它将解决您的问题

I guess the problem is in your .xls file. 我猜问题出在您的.xls文件中。 I have used your code and modified something. 我已经使用了您的代码并修改了一些内容。 Have a look at it, I have check it and it is working 看看,我检查了一下,它正在工作

NSURL *myUrl=[NSURL URLWithString:@"http://www.principlesofeconometrics.com/excel/airline.xls"];
NSURLRequest *myRequest=[NSURLRequest requestWithURL:myUrl];
myData=[[NSMutableData alloc]initWithLength:0];

[NSURLConnection sendAsynchronousRequest:myRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    [myData appendData:data];

    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory=[paths objectAtIndex:0];

    NSString *filename=[documentDirectory stringByAppendingPathComponent:@"samplefile.xls"];
    if ([myData writeToFile:filename atomically:YES]) {
        NSLog(@"Done");
    }
    else
        NSLog(@"Error");

    NSString *str=[documentDirectory stringByAppendingPathComponent:@"samplefile.xls"];
    BOOL fileExists=[[NSFileManager defaultManager]fileExistsAtPath:str];
    NSLog(@"File ----%d",fileExists);

}];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM