例如,我的ftp服务器上有100个JSON文件和100个图像。
1.加载JSON哪里没有bug(我希望)
NSString *recipesPath = @"ftp://.../recipes/";
NSString *recipeFileName = [NSString stringWithFormat:@"00001.json", recipeCode];
NSString *recipeFileFullPath = [recipesPath stringByAppendingString:recipeFileName];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:recipeFileFullPath]];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSError *error = nil;
NSDictionary *recipeDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
2.无法加载图片
NSString *recipeImageName = @"recipeImages/00001-1.jpg";
NSString *recipeImageFullPath = [recipesPath stringByAppendingString:recipeImageName];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:recipeImageFullPath]];
if (request) {
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
if (responseData) {
UIImage *image = [UIImage imageWithData:responseData];
}
}
responseData 几乎总是 nil 。
可能还有另一种方法吗?
所有这些代码都在 MyMethod 中,我在NSOperationQueue
中执行:
operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(MyMethod) object:nil];
[operationQueue addOperation:operation];
编辑:图片尺寸不大 - 从50到100千字节
编辑:可以将图片文件扩展名影响到下载过程吗?
答案 0 :(得分:0)
你可以试试这个:
NSURL *url = [NSURL URLWithString:recipeImageFullPath];
NSData *data = [NSData alloc] initWithContentsOfURL:url];
答案 1 :(得分:0)
请尝试测试一下:
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
/* Return Value
The downloaded data for the URL request. Returns nil if a connection could not be created or if the download fails.
*/
if (responseData == nil) {
// Check for problems
if (requestError != nil) {
...
}
}
else {
// Data was received.. continue processing
}