我在指定的 URL 上有一个文件(没有扩展名)。
我希望能够从此文件中读取每个单独的字节,并将其二进制编码转换为普通的人类可读的十进制。
例子:
从 URL 读取文件 -> 将其加载到缓冲区 -> 读取字节数 20(例如) -> 将其值转换为小数/整数,我可以从那里继续处理. (显示在标签等上)
现在我只能在文件是本地文件时读取文件(使用 NSFileHandle
),但是由于这个文件发生变化,并且通常必须从 URL 读取,所以必须从 URL 加载它的方法。
非常感谢。
//ifraaank
最佳答案
您可以通过多种方式从 URL 中读取资源。在 iOS7 之前,你可以使用 NSURLConnection。这是例子
NSURL *URL = [NSURL URLWithString:@"http://file.com/xxxx"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError
*connectionError) {
if ( !connectionError ){
//transfer the NSData into what you need
}else{
UIAlertView *alert = [UIAlertView alloc]initWithTitle:@"Error"....
}
}];
iOS7之后,还可以使用NSURLSession,这里是例子
NSURL *URL = [NSURL URLWithString:@"http://file.com/xxx"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:
[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionTask *task = [session downloadTaskWithURL:URL
completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
if ( !error){
NSData *data = [NSData dataWithContentsOfURL: location];
//transfer the NSData into what you need
}
}];
[task resume];
希望这对您有所帮助。
编辑: 如果你想从 NSData 中读取字节。你可以作为例子执行
Byte buffer[20];
int bufferLength = 20;
for ( int i= 0; i < [data length] ; i=i+20){
memset(&buffer, 0, 20);
//check the buffer length exceed the end of NSData
bufferLength = (bufferLength > [data length]-i)?(bufferLength = [data length]-i):bufferLength;
[data getBytes:&buffer range:NSMakeRange(i, bufferLength)];
//perform the buffer, it's a Byte[20]
}
关于ios - 从 URL 读取字节,并将二进制转换为普通十进制。对象C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20874910/