I'm doing a simple request in order to download PDF files and then write it to the file path.
Some of the PDF's are getting directed to the fail block.
The error code I'm getting is 200 and the error description is "transfer closed with 2231939 bytes remaining to read".
Below is the code snippet.
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:nil
timeoutInterval:120];
AFHTTPRequestOperation *downloadRequest = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[downloadRequest setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (operation.response.statusCode != 200) {
NSLog(#"Error code(S): %d",[operation.response statusCode]);
}else{
NSData *data = [[NSData alloc] initWithData:responseObject];
[data writeToFile:filePath atomically:YES];
NSLog(#"successful download to %#", filePath);
[data release];
}
[self fetchComplete:operation type:type];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error code: %d",[operation.response statusCode]);
NSLog(#"error discreption: %#",[error localizedDescription]);
[self fetchFailed:operation];
}];
Please, try this example. Hope this help!
// Step 1: create NSURL with full path to downloading file
// for example try this: NSString *fileUrl = #"https://pbs.twimg.com/profile_images/2331579964/jrqzn4q29vwy4mors75s_400x400.png";
// And create NSURLRequest object with our URL
NSURL *URL = [NSURL URLWithString:fileUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
// Step 2: save downloading file's name
// For example our fileName string is equal to 'jrqzn4q29vwy4mors75s_400x400.png'
NSString *fileName = [URL lastPathComponent];
// Step 3: create AFHTTPRequestOperation object with our request
AFHTTPRequestOperation *downloadRequest = [[AFHTTPRequestOperation alloc] initWithRequest:request];
// Step 4: set handling for answer from server and errors with request
[downloadRequest setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// here we must create NSData object with received data...
NSData *data = [[NSData alloc] initWithData:responseObject];
// ... and save this object as file
// Here 'pathToFile' must be path to directory 'Documents' on your device + filename, of course
[data writeToFile:pathToFile atomically:YES];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"file downloading error : %#", [error localizedDescription]);
}];
// Step 5: begin asynchronous download
[downloadRequest start];
Related
unable to download file
getting this error "Client closed connection before receiving entire response"
the file which i am trying to download is just 266KB
for (NSString *downloadURL in arr) {
// NSString *downloadURL = [d objectForKey:#"url"];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"URL for downloading : %#",downloadURL);
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *documentsDirectory = [pathArray objectAtIndex:0];
NSString *downloadedZipPath = [documentsDirectory stringByAppendingPathComponent:TEMP_DICTIONARY];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:downloadURL]];
// [request addValue:#"bytes=x-" forHTTPHeaderField:#"Range"];
// [request setTimeoutInterval:20];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:downloadedZipPath append:NO];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[operation start];
});
tried to increase api request time out but still not working
Try setting it to more time
[request setTimeoutInterval:20];
I have some error like this. But I think it is not the AF faults. When the thing's content-type you request is different from it's original content type this error will come out.
For Example:
When you request a mp4 file, the server should set the content-type to video/mpeg4, or you can change your request type from GET to POST.
Here below is my jsp call:
NSString *strURL = [NSString stringWithFormat:#"https://xxx.com/xx/jsp/Implementation/getMyResource.jsp?uid=xxxxx"];
NSURL *urlLink = [[NSURL alloc] initWithString:strURL];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:urlLink];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
operation.responseSerializer = [AFXMLParserResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSXMLParser *xmlParser = (NSXMLParser*)responseObject;
NSLog(#"%#",xmlParser);
NSError * parsedError = nil;
NSDictionary *dictUserDetails = [XMLReader dictionaryForNSXMLParser:xmlParser error:&parsedError];
if (parsedError == nil) {
NSLog(#"%#",dictUserDetails);
}
else
{
NSLog(#"wrong while parsing xml data");
}
} failure:^(AFHTTPRequestOperation *request, NSError *error){
NSLog(#"Error:------>%#", [error description]);
}];
No response at all. When i paste strURL link in web browser i get response instantly, so no problem in url.
You need to add your AFHTTPRequestOperation to the queue:
[[NSOperationQueue mainQueue] addOperation:operation];
See https://github.com/AFNetworking/AFNetworking#get-with-afhttprequestoperation
I am having a hard time sifting through search results for how to do this and I can't find anything concrete in the documentation. I just want to download a file and store in the Documents directory. The file is of type .plist, but I don't need to parse the plist. Like I said I just need to save it to disk.
Do I use AFHTTPRequestOperationManager for this?
This is what I've been trying in general:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//manager.responseSerializer = [AFPropertyListResponseSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:url parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
DLog(#"downloaded plist");
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DLog(#"JSON DataError: %#", error);
}];
If I use AFHTTPResponseSerializer I get this:
Error Domain=AFNetworkingErrorDomain Code=-1011 "Request failed: internal server error (500)"
If I use AFPropertyListResponseSerializer I get this:
Error Domain=AFNetworkingErrorDomain Code=-1016 "Request failed: unacceptable content-type: text/plain"
But I'm not even sure I'm using the correct API.
Please, try this example.
Hope this help!
// Step 1: create NSURL with full path to downloading file
// for example try this: NSString *fileUrl = #"https://pbs.twimg.com/profile_images/2331579964/jrqzn4q29vwy4mors75s_400x400.png";
// And create NSURLRequest object with our URL
NSURL *URL = [NSURL URLWithString:fileUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
// Step 2: save downloading file's name
// For example our fileName string is equal to 'jrqzn4q29vwy4mors75s_400x400.png'
NSString *fileName = [URL lastPathComponent];
// Step 3: create AFHTTPRequestOperation object with our request
AFHTTPRequestOperation *downloadRequest = [[AFHTTPRequestOperation alloc] initWithRequest:request];
// Step 4: set handling for answer from server and errors with request
[downloadRequest setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// here we must create NSData object with received data...
NSData *data = [[NSData alloc] initWithData:responseObject];
// ... and save this object as file
// Here 'pathToFile' must be path to directory 'Documents' on your device + filename, of course
[data writeToFile:pathToFile atomically:YES];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"file downloading error : %#", [error localizedDescription]);
}];
// Step 5: begin asynchronous download
[downloadRequest start];
Something else: What's the best way to find the user's Documents directory on an iPhone?
I have a requirement where i am uploading a wave file on server and server gives me back the URL of that file.
I have used this Codes..
- (void)callUploadWS
{
NSString *vidURL = [[NSBundle mainBundle] pathForResource:#"alarm" ofType:#"wav"];
NSData *videoData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:vidURL]];
NSURL *url = [NSURL URLWithString:#"http://6.6.237.190"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
// NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:#"Romantic.jpg"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:#"/recorder/convert.php" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:videoData name:#"file" fileName:#"speech.wav" mimeType:#"audio/vnd.wave"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(#"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
// [httpClient enqueueHTTPRequestOperation:operation];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {NSLog(#"Success : %#",responseObject);}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", operation.responseString);
NSLog(#"error: %#", error.userInfo);
}];
[operation start];
}
Its uploading file and giving me this response...
Success : <7b226669 6c65223a 22687474 703a5c2f 5c2f352e 392e3233 372e3135 305c2f72 65636f72 6465725c 2f75706c 6f61645c 2f353237 32336564 32366531 63662e77 6176227d>
But it should give response like this..
{
file: "http://6.6.237.190/recorder/upload/52723ef52972d.wav"
}
why this gives binary response?
You have to convert the responseObject to NSString like this
NSString *responseString=[NSString stringWithUTF8String:[responseObject bytes]];
#Gagan Kumar has given really nice answer but its half code. It will convert your json response to a String.
So you are not be able to get the dictionary from that and not able to parse the file URL. For doing that you have to reserialize the String to json using this code..
NSString *responseString=[NSString stringWithUTF8String:[responseObject bytes]];
NSError *e = nil;
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData: [responseString dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: &e];
if (e) {
NSLog(#"error : %#",e);
}else{
NSLog(#"JSON : %#",JSON);
}
This will return the json object which will be parsable.
Hope it help.
I'm trying to compile application on my iPad. I'm using AFNetworking to get list of files on my FTP. Application works on simulator, but when i start it on iPad i get (null) content of file with list. Here's code:
- (void) getListOfFiles {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"ftp://anonymous#ftphost/"]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSString *path = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:#"list"];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:YES];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, NSHTTPURLResponse *response) {
NSLog(#"Success %#",operation.response);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error localizedDescription]);
}];
[operation start];
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSLog (#"%#",content);
}
So variable content = (null) only on iPad, and on Simulator everything is fine. Please help, i have lost any hope )
the AFHTTP*Operations are all asynchronous by default.
this is proper, since synchronous(blocking) calls block the main thread
you are starting the operation and take file content directly afterwards. This can't work reliably because the start call is ASYNC and only STARTS the op but doesnt wait for it
either wait for it ... which is BAD as it blocks the thread:
[operation start];
[operation waitUntilDone];
or MUCH BETTER modify getFiles to work asynchronously:
- (void) getListOfFiles {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"URL"]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSString *path = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:#"list"];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:YES];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, NSHTTPURLResponse *response) {
NSLog(#"Success %#",operation.response);
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSLog (#"%#",content);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error localizedDescription]);
}];
[operation start];
}
Ok, problem solved. I can't write to bundle directory, so i nee to use next code instead:
NSArray *paths = NSSearchPathForDirectoiesDomain(NSDocumentDirectory,NSCachesDirectory,YES);
NSString *path = [[paths objectAtIndex:0] stingByAppendingPathComponent:#"list"];