I am currently developing an iOS app that allows a user to post a classified listing for other users to see. On all devices, that app hangs in a "O% Uploaded" SVProgressHUD for a while before displaying "Our server is temporarily unavailable. Please try again later.", which is what I have coded in the case of a Status Code 500 error from the server side. However, on the iOS simulator, everything works smoothly.
All other functionality involving network requests is working perfectly except for this, so it must have something to do with the actual upload process. I've posted the corresponding code below; if you require anything additional to help figure this out, please let me know.
Networking Code
- (IBAction)publishPressed:(UIBarButtonItem *)sender {
[SVProgressHUD showWithStatus:#"Loading..." maskType:SVProgressHUDMaskTypeBlack];
// Set the params for the API call in an NSMutableDictionary called mutableParams.
// Create the form request with the post parameters and image data to pass to the API.
NSMutableURLRequest *request = [[UAPIClient sharedClient] multipartFormRequestWithMethod:#"POST"
path:#"mobPost.php"
parameters:mutableParams
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if (self.imageHasBeenSet) {
[self.listingImageView.image fixOrientation];
NSData *imageData = UIImagePNGRepresentation(self.listingImageView.image);
[formData appendPartWithFileData:imageData name:#"userfile"
fileName:#"postImage.png" mimeType:#"image/png"];
}
}];
// Create the `AFJSONRequestOperation` from the form request, with appropriate success and failure blocks.
AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseJSON) {
if ([[responseJSON objectForKey:#"status"] intValue] == 1) {
dispatch_async(dispatch_get_main_queue(), ^{
[SVProgressHUD showSuccessWithStatus:#"Success!"];
});
// Pass a message back to the delegate so that the modal view controller
// can be dismissed successfully.
[self.delegate uCreateListingTableViewController:self didCreateListing:YES];
} else {
dispatch_async(dispatch_get_main_queue(), ^{
[SVProgressHUD showErrorWithStatus:#"Post failed. Please try again."];
});
NSLog(#"Status %#", [responseJSON objectForKey:#"status"]);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
dispatch_async(dispatch_get_main_queue(), ^{
[SVProgressHUD showErrorWithStatus:#"Our server is temporarily unavailable. Please try again later."];
});
}];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
dispatch_async(dispatch_get_main_queue(), ^{
[SVProgressHUD showSuccessWithStatus:[[NSString stringWithFormat:#"%lli", (totalBytesWritten / totalBytesExpectedToWrite)] stringByAppendingString:#"% Uploaded"]];
});
}];
[[UAPIClient sharedClient] enqueueHTTPRequestOperation:operation];
}
UAPIClient.m
#import "UAPIClient.h"
#import "AFJSONRequestOperation.h"
static NSString * const kUAPIBaseURLString = #"hiding string for privacy";
#implementation UAPIClient
+ (UAPIClient *)sharedClient {
static UAPIClient *_sharedClient;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedClient = [[UAPIClient alloc] initWithBaseURL:[NSURL URLWithString:kUAPIBaseURLString]];
});
return _sharedClient;
}
- (id)initWithBaseURL:(NSURL *)url {
self = [super initWithBaseURL:url];
if (self) {
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
// Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
[self setDefaultHeader:#"Accept" value:#"application/json"];
}
return self;
}
#end
Related
I am making a simple GET request using AFNetworking 2, but I am getting a NSURLErrorDomain error.
I created a manager class which subclasses AFHTTPRequestOperationManager and creates a singleton instance so that I can use a shared manager.
+ (id)manager {
static dispatch_once_t pred = 0;
__strong static id _sharedObject = nil;
dispatch_once(&pred, ^{
_sharedObject = [[self alloc] init];
});
return _sharedObject;
}
- (id)init {
NSURL *baseURL = [ZSSAuthentication baseURL];
self = [super initWithBaseURL:baseURL];
if (self) {
[self setRequestSerializer:[AFJSONRequestSerializer serializer]];
[self setResponseSerializer:[AFJSONResponseSerializer serializer]];
[self.requestSerializer setAuthorizationHeaderFieldWithUsername:[ZSSAuthentication username] password:[ZSSAuthentication password]];
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
}
return self;
}
- (void)getData:(NSString *)pubID parameters:(NSDictionary *)parameters completion:(void (^)(NSDictionary *results))completion failure:(void (^)(NSError *error))failure {
NSString *url = [NSString stringWithFormat:#"data/all/%#", pubID];
[self GET:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
// Check to see if there are errors
ZSSError *error = [self errorForAPICall:responseObject status:[operation.response statusCode]];
if (error) {
[self logMessage:error.localizedDescription];
failure(error);
return;
}
NSDictionary *data = [responseObject objectForKey:#"data"];
completion(data);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
failure(error);
}];
}
Then, in my viewController's viewDidLoad method I make a call to that method:
[[ZSSManager manager] getData:self.pubID parameters:nil completion:^(NSDictionary *results) {
self.items = results;
[self dataWillReload];
NSLog(#"%#", results);
[self.tableView reloadData];
} failure:^(NSError *error) {
NSLog(#"Error: %# %li", error, (long)error.code);
}];
Then I get this error:
Error Domain=NSURLErrorDomain Code=-999 "The operation couldn’t be completed. (NSURLErrorDomain error -999.)" UserInfo=0x7ff952306610 {NSErrorFailingURLKey=http://test.mysite.com/v1/data/all/5}
The strange thing is, on a previous viewController, I make a different call to the manager, and it completes and returns data correctly. But, when I make this second call, I get the error. AND, if I move that getData call out of the viewDidLoad method, and invoke it with a button press, it DOES WORK. What the heck?
What could be causing this?
I am trying to implement AFNetworking code to communicate with a web API. I am getting the following errors in the code:
No visible #interface for APIClass declares the selector
registerHTTPOperationClass
No visible #interface for APIClass declares the selector
setDefaultHeader:Value
No visible #interface for APIClass declares the selector
multiPartFormRequestWithMethod:path:parameters:constructingBodyWithblock
Obviously something to do with the new AFNetworking 2.0 migration...however I have been looking at all the migration posts and documentation and connot find the replacements for these without throwing an error:
// add the location details of the web service we wrote
#define kAPIHost #"http://myurl"
#define kAPIPath #"mywebapi/"
#implementation APIClass
// this is the implementation of the singleton method
+(APIClass*)sharedInstance{
static APIClass *sharedInstance = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
sharedInstance = [[self alloc] initWithBaseURL:[NSURL URLWithString:kAPIHost]];
});
return sharedInstance;
}
-(APIClass*)init{
// call super init
self = [super init];
if (self != nil){
user = nil;
[self registerHTTPOperationClass:[AFHTTPRequestOperation class]];
// Accept HTTP header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
[self setDefaultHeader:#"Accept" value:#"application/json"];
}
return self;
}
// call to the server
-(void)commandWithParams:(NSMutableDictionary*)params onCompletion:
(JSONResponseBlock)completionBlock
{
// prepare e POST request by creating an NSMutableURLRequest instance using the
// parameters we want to send via POST
NSMutableURLRequest *apiRequest =
[self multipartFormRequestWithMethod:#"POST"
path:kAPIPath
parameters: params
constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
// attach file if needed
}];
// create an operation to handle the network communication in the background
// and intialize it with the POST request we just prepared
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:
apiRequest];
// now set the 2 blocks needed for success and failure
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id
responseObject)
{
// success! - if the call is successful then we just pass in the JSON response
NSLog(#"responseObject: %#", responseObject);
completionBlock(responseObject);
}
// if there is a failure in the network call then we call the failure block
// and contrcut a new dictinary to hold the message of the network error
failure:^(AFHTTPRequestOperation *operation, NSError * error) {
//failure!
completionBlock([NSDictionary dictionaryWithObject:[error localizedDescription]forKey:#"error"]);
}];
// at this point we can call the start method so that AFNetworking can do its
// magic in the background
[operation start];
}
#end
You're getting these errors because the methods you're calling aren't methods of whatever class you're subclassing. I'll assume you're subclassing AFHTTPSessionManager, which is recommended for iOS 7 in AFNetworking 2.0. Based on that...
For your first two errors, I believe the updated lines below are the AFNetworking 2.0 way of doing it with AFHTTPSessionManager:
-(APIClass*)init{
// call super init
self = [super init];
if (self != nil){
user = nil;
self.requestSerializer = [AFJSONRequestSerializer serializer];
self.responseSerializer = [AFJSONResponseSerializer serializer];
}
}
For your third error, the method multiPartFormRequestWithMethod:path:parameters:constructingBodyWithblock should be replaced with:
[self POST:kAPIPath parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
// attach file if needed
} success:^(NSURLSessionDataTask *task, id responseObject) {
// handle success
} failure:^(NSURLSessionDataTask *task, NSError *error) {
// handle failure
}];
First off: I'm quite new to RestKit so perhaps this is an easy question to solve.
I am trying to download a lot of files. Currently I use the getObjectsAtPath:parameters:success:failure: method of RKObjectManager to fetch and map my objects towards restkit.
However, It seems as it starts some downloads prematurely and then timesout when they are in the queue.
The code I am using:
- (void)removeResponseAndRequestDescriptors
{
RKObjectManager *objectManager = [RKObjectManager sharedManager];
[objectManager.requestDescriptors enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[objectManager removeRequestDescriptor:obj];
}];
[objectManager.responseDescriptors enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[objectManager removeResponseDescriptor:obj];
}];
}
.
- (void)downloadAudioFileForAudio:(IBAudio *)audio
inBook:(IBBook *)book
downloadStatus:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))downloadStatus
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
RKObjectManager *objectManager = [RKObjectManager sharedManager];
NSString *sessionID = (book.parent ? book.parent.user.session.sessionID : book.user.session.sessionID);
[objectManager.HTTPClient setDefaultHeader:#"Accept" value:#"application/octet-stream"];
[objectManager.HTTPClient setDefaultHeader:#"Session-Id" value:sessionID];
[objectManager.HTTPClient getPath:[IBProperties downloadAudioEndPointWithIsbn:book.isbn andAnchor:audio.anchor] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *folderPath = [self folderPathForBook:book];
NSString *audioPath = [folderPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.mp3", audio.anchor]];
NSData *audioData = [NSData dataWithData:responseObject];
NSError *fileSystemSaveError;
[self saveFile:audioData toFilePath:audioPath error:&fileSystemSaveError];
if (fileSystemSaveError) {
failure(fileSystemSaveError);
return;
}
// Saving the context asap in case the app dies before it can autosave.
NSError *coreDataSaveerror;
[[[[RKObjectManager sharedManager] managedObjectStore] mainQueueManagedObjectContext] save:&coreDataSaveerror];
if (coreDataSaveerror) {
failure(coreDataSaveerror);
return;
}
[audio setFilePath:audioPath];
success();
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
failure(error);
}];
[objectManager.HTTPClient.operationQueue.operations.lastObject setDownloadProgressBlock:downloadStatus];
}
.
- (void)downloadAudioFiles
{
for (IBAudio *audio in self.book.bookData.audios) {
self.numberOfDownloads++;
[self.downloadPercentagesFiles addObject:[[IBDownloadStatusOfAFile alloc] init]];
NSInteger arrayIndex = [self.downloadPercentagesFiles count] - 1;
[[IBDataBackendFetcher sharedBackendFetcher] downloadAudioFileForAudio:audio inBook:self.book downloadStatus:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
IBDownloadStatusOfAFile *statusOfFile = [self.downloadPercentagesFiles objectAtIndex:arrayIndex];
statusOfFile.bytesRead = bytesRead;
statusOfFile.totalBytesRead = totalBytesRead;
statusOfFile.totalBytesExpectedToRead = totalBytesExpectedToRead;
[self updateDownloadProgress];
} success:^{
[self downloadDidComplete];
} failure:^(NSError *error) {
[self.dataProviderDelegate downloadDidFailWithError:error forBookDownloader:self];
}];
}
}
It seems as it starts all downloads at once, but the actuall download is not started. So the last downloads gets a timeout.
Is there a better way for do this to solve this problem?
All the downloads will run simultaneously, because you're making all the getPath: calls right in a row (they are asynchronous calls). Since each download takes a while to finish, this causes the timeout on the later calls.
If you want each download to occur only after the previous one completes, I would make a method called getNextAudioFile: and an iterator class property. Then, in both the success and failure blocks of getPath:, increment your iterator and call getNextAudioFile:.
Example code:
- (void)downloadAudioFiles
{
// No for loop
self.iterator = 0;
// your call to DownloadAudioFileForAudio: ... for the first audio goes here
}
- (void)downloadAudioFileForAudio:(IBAudio *)audio
inBook:(IBBook *)book
downloadStatus:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))downloadStatus
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
// your code ...
[objectManager.HTTPClient getPath:[IBProperties downloadAudioEndPointWithIsbn:book.isbn andAnchor:audio.anchor] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject){
// your code...
// increment and get the next file
self.iterator++;
[self getNextAudioFile];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
failure(error);
// increment and get the next file
self.iterator++;
[self getNextAudioFile];
}];
}
- (void)getNextAudioFile
{
if(self.iterator < [self.book.bookData.audios count]){
// make your downloadAudioFileForAudio: call for the next audio
}
}
That's the idea at least! Hope it helped.
Set the maximum number of concurrent operation on the queue to some reasonable value like 5.
[objectManager.HTTPClient.operationQueue setMaxConcurrentOperationCount:5];
(before you start any requests)
I want to perform an upload task once a user has selected a share activity from UIActivityViewController, but before the share sheet is shown.
Specifically, I need the url of the uploaded image to use in the Activity.
I already have subclassed UIActivityItemProvider and figure I can do my uploading in the itemForActivityType method, however the uploading code is block based and I can't figure out how to make it wait for the block to finish. Is this even possible?
It might be a simple coding error, it's been a long day.
I dont want to upload the image when the user presses the share button, as they might cancel the Activity View which means the uploaded image is sitting there not being used.
This is the code I currently have, but it returns nil before the image has uploaded and within the block it doesn't let me return nil for the errors:
- (id) activityViewController:(UIActivityViewController *)activityViewController itemForActivityType:(NSString *)activityType
{
[self getShortUrlForUploadedImageWithCompletionHandler:^(NSString *shortUrl, NSError *error) {
if (!error) {
if ( [activityType isEqualToString:UIActivityTypeMail] ) {
NSString *shareString = #"Email content here using shortUrl";
return shareString;
} else {
return #"";
}
} else {
return #"";
}
}];
return nil;
}
-(void)getShortUrlForUploadedImageWithCompletionHandler:(NSString* (^)(NSString *shortUrl, NSError *error))completionHandler
{
NSData *imageToUpload = UIImageJPEGRepresentation(_image, 75);
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:kShareURL]];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
#"image", #"action",
#"simple", #"format",
nil];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:nil parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData: imageToUpload name:#"image" fileName:#"temp.png" mimeType:#"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *response = [operation responseString];
NSLog(#"response: %#",response);
completionHandler(response, nil);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if([operation.response statusCode] == 403){
NSLog(#"Upload Failed");
return;
}
NSLog(#"error: %#", [operation error]);
completionHandler(nil, error);
}];
[operation start];
}
-------- EDIT
I really could do with some help on this. My current work around is to upload the image when the user click my share button, before the Activity selection. So they could cancel the share and i'm left with a redundant uploaded image, or they could select Twitter which doesn't need the uploaded image.
I need to only upload the image if Email has been selected and I think the only place I can do this is in the Acticity Provider subclass.
Instead of implementing - (id)activityViewController:(UIActivityViewController *)activityViewController itemForActivityType:(NSString *)activityType, try overriding the UIActivityItemProvider's - (id)item. This method will be called from the NSOperation's main method which is on a background thread.
As for waiting until the networking completion block triggers, I'd recommend you look into using a dispatch_semaphore. Here is an example:
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(#"doing some work");
sleep(5);
NSLog(#"done with work");
dispatch_semaphore_signal(semaphore);
});
double delayInSeconds = 60.0;
dispatch_time_t waitTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
NSLog(#"waiting for background thread to finish");
dispatch_semaphore_wait(semaphore, waitTime);
NSLog(#"background thread finished, or took too long");
Make sure to only use this on a background thread though, otherwise you will block the main thread.
So after much research I figured out how to send a NSDictionary from my iOS 6 client to my rails server. I used AFNetworking. Below is the client side code that sends the JSON. However, Im not sure if this is an asynchronous call since I dont see where an operation queue is being used. If it isn't then how do I make it into an asynchronous call?
-(void)sendEntryToServerAsJSON:(EntryParent*)_entryToBeSaved
{
NSDictionary* dictToBeSerialized = [_entryToBeSaved convertEntryParentObjToDict];
[[appAPIClient sharedClient]postPath:#"entries.json"
parameters:dictToBeSerialized
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Successfully sent JSON %#", [responseObject description]);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Could not send JSON %#", [error description]);
}];
}
Here is my implementation of the AFHTTPClient
+ (appAPIClient *)sharedClient
{
NSLog(#"Inside appAPIClient sharedclient ");
static appAPIClient *_sharedClient = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedClient = [[self alloc]
initWithBaseURL:[NSURL URLWithString:URL_STR]];
});
return _sharedClient;
}
//==============================================================================
- (id)initWithBaseURL:(NSURL *)url
{
self = [super initWithBaseURL:url];
if (!self)
{
return nil;
}
NSLog(#"init with base url - appAPIClient");
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
// Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
[self setDefaultHeader:#"Accept" value:#"application/json"];
return self;
}
I would appreciate any feedback to improve this code and make it asynchronous.
to a)
the requests are added to the main threads runloop so they are async without a thread or queue. runloops are kinda like C's select method
see:
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSRunLoop_Class/Reference/Reference.html
to b) please make into a separate question :)