mugunthkumar / mknetworkkit Goto Github PK
View Code? Open in Web Editor NEWModern NSURLSession based Networking Framework with built in authentication and HTTP 1.1 caching standards support for iOS 8+ devices
Home Page: http://mk.sg/8w
Modern NSURLSession based Networking Framework with built in authentication and HTTP 1.1 caching standards support for iOS 8+ devices
Home Page: http://mk.sg/8w
Hi, I used the anazlyzer to detect memory leaks and it showed 2 in NSString+MKNetworkKitAdditions.m, Someone has dealed with this before and fixed it?, please let me know, its really urgent :S
(NSString_) uniqueString
{
CFUUIDRef uuidObj = CFUUIDCreate(nil);//create a new UUID
//get the string representation of the UUID
NSString *uuidString = (_bridge NSString)CFUUIDCreateString(nil, uuidObj);
//if (uuidString != nil)
CFRelease(uuidObj);
return uuidString; //In this line appears the leak: Potential leak of an object allocated on line 49 and stored
// into 'uuidString'
}
(NSString*) urlEncodedString {
CFStringRef encodedString = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(__bridge CFStringRef) self,
nil,
CFSTR("?!@#$^&%_+,:;='"`<>()[]{}/|~ "),
kCFStringEncodingUTF8);
if (encodedString) {
return (_bridge_transfer NSString) encodedString; //In this line appears the leak:Address of stack memory
} //associated with local variable 'encodedString' returned to
return @""; //caller
}
I'm having trouble in my OCUNIt testing code that invokes MKNetworkEngine code. The networkEngine calls become extremely slow when run in unit testing mode (I've setup a logic unit testing target that only invokes the MKNetworkEngine code). Sometimes the operations take as much as 5 mins to complete. Any one have similar issues?
I'd like to have the Request body be Image Data. I do not want to use multipart form-data, but rather just add the raw image data to the HTTPBody.
Is this possible?
@Property (copy, nonatomic) void (^operationStateChangedHandler)(MKNetworkOperationState newState);
MKNetworkOperationState is declared in MKNetworkOperation.m. Shouldn't it be moved into MKNetworkOperation.h?
Need to debug this
This crash is only on iOS 4.3
I get signal SiGABRT on this method: NSString *filePath = [[self cacheDirectoryName] stringByAppendingPathComponent:lastKey];
2012-02-24 16:52:52.763 [13399:18e0b] -[**NSDate length]: unrecognized selector sent to instance 0x677b760
2012-02-24 16:52:52.765 [13399:18e0b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDate length]: unrecognized selector sent to instance 0x677b760'
* Call stack at first throw:
(
0 CoreFoundation 0x023375a9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x01e02313 objc_exception_throw + 44
2 CoreFoundation 0x023390bb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
3 CoreFoundation 0x022a8966 __forwarding + 966
4 CoreFoundation 0x022a8522 _CF_forwarding_prep_0 + 50
5 Foundation 0x018581ad -[NSPathStore2 stringByAppendingPathComponent:] + 211
6 0x0002622b -[MKNetworkEngine saveCacheData:forKey:] + 1003
7 0x00024101 -[MKNetworkEngine cachedDataForOperation:] + 577
8 0x00024665 __48-[MKNetworkEngine enqueueOperation:forceReload:]_block_invoke_0 + 309
9 libdispatch_sim.dylib 0x01da6289 _dispatch_call_block_and_release + 16
10 libdispatch_sim.dylib 0x01da958a _dispatch_worker_thread2 + 252
11 libsystem_c.dylib 0x9ae38b24 _pthread_wqthread + 346
12 libsystem_c.dylib 0x9ae3a6fe start_wqthread + 30
)
terminate called throwing an exception(lldb)
(lldb)
(lldb) po lastKey
(NSString *) $5 = 0x0677b760 2012-02-10 11:13:29 +0000
(lldb) po self cacheMemoryCost $6 = 10
(lldb) po [self cacheDirectoryName](NSString *) $7 = 0x0718e220 /Users/Rudy/Library/Application Support/iPhone Simulator/4.3.2/Applications/BEB6D1D9-6A32-4FCD-8EA8-E156C6835FA1/Library/Caches/MKNetworkKitCache
(lldb) po [[self cacheDirectoryName] stringByAppendingPathComponent:lastKey]
2012-02-24 16:54:20.508 [13399:18e0b] -[__NSDate length]: unrecognized selector sent to instance 0x677b760
(id) $8 = 0x00000000
(lldb) po lastKey
(NSString *) $9 = 0x0677b760 2012-02-10 11:13:29 +0000
(lldb)
This is related to issue 45.
MKNetworkKit.encodedPostDataString returns a string, as does postDataEncodingHandler. This means there's no opportunity to return an NSData. There should be a way to do this.
--Eric
I've already mentioned on twitter, the definition of ELog
macro is dangerous.
ELog
is defined as:
#define ELog(err) if (err) DLog(@"%@", err)
Consider the following usage:
if (someCondition)
ELog(err);
else
SomeAction();
The if
inside ELog
will act with else
in a way not intended by developer.
The workaround for this issue is the same as used in assert macros:
#define ELog(err) do { if (err) DLog(@"%@", err); } while (0)
Hi
im trying to use your example to build a image loading application, but i got this strange problem, after the images are loaded and the table it's refreshing it's showing all king of images instead of right ones, this just happens first time when cache is empty, after that if you try to reload the images, the thumbs are fine.
Small bug: if you try to send a POST request with an empty body, it crashes.
The problem is that in the MKNetworkOperation
initialization method you set fieldsToBePosted
to [NSMutableArray array]
, when it should be [NSMutableDictionary dictionary]
. Making this change fixes the problem.
For method POST, MKNetworkOperation initStringWithUrlString sets the Content-Type header to "application/x-www-form-urlencoded; charset=utf-8." The server I am testing blows up with "HTTP 501 Not Implemented. Incorrect Type." If I modify that method to remove the charset parameter, it works fine.
I have not encountered this before so searched the net. I found a few discussions that charset should not be included in the Content-Type header for application/x-www-form-urlencoded. Example which includes "no browser has ever supplied a charset parameter with the application/x-www-form-urlencoded media type. What's more, the HTML spec which defines that type, does not propose a charset parameter, so the server can't reasonably expect to get one."
I can't vouch for the accuracy of this information, and am certainly not an http/html expert, but eliminating the charset solved my problem. The W3C XForms spec describes charset for each element of multipart/form-data, but not for application/x-www-form-urlencoded.
http://www.w3.org/TR/2003/REC-xforms-20031014/slice11.html#serialize-urlencode
Is this a special case, or should MKNetworkOperation initStringWithUrlString be revised to eliminate charset for Content-Type application/x-www-form-urlencoded?
I have added MKNetworkKit to my proj and compile successfully. but I alway got a exception when I run at enqueueOperation method, and I found the error message is "It'sMyCoupon[14358:11003] -[__NSCFString md5]: unrecognized selector sent to instance 0x8a54d40", but I am very sure I can see and use the "- (NSString *) md5" method in NSString+MKNetworkAddtional.h, who have ever been met this?
I'm currently writing an OAuth consumer that uses MKNetworkKit. I'm using several properties from MKNetworkOperation, and the only info that I can't find a simple way to obtain is the HTTP Method of the request.
I know I could get it from readonlyRequest
, but since it copies the whole request to a new instance I believe it's overkill to use it. I also didn't want to fork the whole project just to add one property (unless that's how I should use GitHub, I'm kinda new to all this) so currently I just added the property to my local copy. But since I want to release my code later, it would be better if it could work with MKNetworkKit without needing any modifications.
Is there any chance you could add such property to this project? Here's how I implemented it (inside MKNetworkOperation):
@property (nonatomic, readonly) NSString *HTTPMethod;
-(NSString*) HTTPMethod {
return self.request.HTTPMethod;
}
Thanks!
Hi:
I have a question about set the post request body using JSON.
how can i send a post request, with body using (NSMutableArray_) as a param.
Now It seems that I can only using (NSMutableDictionary_) as a param.
This really puzzles me .
Is there any API for me to put a Array into the post body
or I have to override some function.
thanks a lot~
Event first start is too slow, because reading images from files in main UI thread.
Please move file reading in background thread thigh completion callback, like NSURLRequest.
If I download an XML file is written to the cache. When I update the xml file (with the same filename) is not overwritten in the file cache.
It creates a new file in the cache with a new identifier, but the application retrieves from the cache always
the first file created in the cache.
My test:
Download a file test.xml and close app, modify file test.xml, open the app, download new file and close app.
Turn wi-fi off, open the app, I see first the test.xml obsolete.
MKNetworkOperation.m line 518 : switch (self.postDataEncoding) {
It's always 0, so calls to JSON RPC don't work, please fix?
Marin
Hello,
When I set the operation.postDataEncoding to MKNKPostDataEncodingTypeJSON I would expect the Content-Type header to be text/plain instead it is application/x-www-form-urlencoded. This is a problem for server scripts looking into the raw data of the request body.
The problem is that the setting of the Content-Type happens in the init method of the operation, so before we get a chance to set the encoding type of the operation, hence it always defaults to the same setting: application/x-www-form-urlencoded.
Workaround : I extended the init method to take the encoding as a parameter which allows me to set it before the Content-Type is set.
Regards,
A.
Hello, if you provide a combination of wrong username and/or wrong password to a MKNetworkOperation, i.e.
MKNetworkOperation *op = [self operationWithURLString:@"http://someurl/"
params:nil
httpMethod:@"GET"];
[op setUsername:@"wrong" password:@"also wrong"];
you will achieve and endless loop between the NSURLConnectionDelegate method connection:willSendRequestForAuthenticationChallenge: providing those wrong credentials and the server faithfully responding with http error 401 credential challenge, triggering the delegate method again. Probably you should introduce some authenticationRetryCount, increase it in connection:willSendRequestForAuthenticationChallenge: and make the MKNetworkOperation fail if authenticationRetryCount reaches 2.
Cheers,
Thomas
This one has had me stumped for a little while. I have an MKNetworkOperation that is set to POST with an NSDictionary of parameters. Once that's been created, I use addData:ForKey: to add some raw UIImage data to the post as I'm uploading an image. On WiFi this works perfectly, but on anything else the POST parameters aren't being sent (which means my API denies it as an authentication key is being sent).
I've tried to have a look at working out why this should work on WiFi but not 3G and not got anywhere with it.
I try to connect to an SSL and Basic Auth secured web service. Connecting works, but it seems to use some earlier stored/cached credentials. When I entered other or simply wrong credentials, I can still connect.
Here's my first attempt using the HTTP Auth header:
MKNetworkOperation *op = [self operationWithPath:path params:nil httpMethod:@"GET" ssl:YES];
[op setUsername:username password:password basicAuth:YES];
I also tried to respond to an auth challenge with my custom handler:
MKNetworkOperation *op = [self operationWithPath:path params:nil httpMethod:@"GET" ssl:YES];
op.authHandler = ^(NSURLAuthenticationChallenge *challenge) {
NSURLCredential *credential = [NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceNone];
[challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
};
In both cases, I can pass wrong username/password and it still connects! In the second case, the custom handler is never called.
I could also see the MKNetworkOperation receive an authentication challenge (in spite of sending my Basic HTTP Auth header). Inside the method (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
it takes the branch
else if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust)
...
I just can't delete the old credentials (that were supposedly stored on my first ever connect) and/or pass different credentials. Maybe I just misunderstood something.
The NSAlert is not available in iOS. This is causing issues when installing by following the instructions here:
http://blog.mugunthkumar.com/products/ios-framework-introducing-mknetworkkit/
It's possible, especially with image requests that are cancelled when scrolled of screen, to crash the enqueue method when you scroll up rapidly (tap the status bar). What happens is since the enqueue operation is asynchronous (for cache perf reasons), the operation can get cancelled before it's enqueued (or in the middle of being enqueued).
I'm looking into a fix.
Hey,
Is there a way to get the redirectURL, when this method will be send:
-[MKNetworkOperation connection:willSendRequest:redirectResponse:] [Line 1017] Redirected to ...
With operation.url I only get the original URL..
Thanks
Michael
In the following idiom:
MKNetworkOperation * op = [[MKNetworkOperation] alloc] initWithURLString:...
There's no opportunity to set op.postDataEncoding, which means the code in initWithURLString to set the relevant headers won't ever be called. The encoding should probably be passed as a parameter.
Hello,
I noticed a weird caching behavior when trying to consume an ASPX page, it goes like this:
1- MKNetworkKit GETs the page and caches it, all good.
2- MKNetworkKit returns the cached version everytime a request is made while the page is not updated.
3- When the page is updated MKNetworkKit first returns the cached version then the updated version once it is finished downloaded, although the weird bit is that this one doesn't replace the first one in the cache.
4- When the page is requested again MKNetworkKit returns the version that was cached the first time, then downloads the page again.
I am using MKNetworkEngine directly, not subclassing it. I also checked the headers of the file and found Cache-Control: private in it, I don't know if it matters.
The server I'm working with has a custom username/pw authentication (using json) and returns a 401 for certain cases with a json response body that I need to handle, for example multifactor authentication. connectionDidFinishLoading ends up calling errorBlock for a 401. Since errorBlock only gets a NSError, the block can't inspect the response.
Could MKNKErrorBlock also be passed the MKNetworkOperation? Then my errorBlock could see if it was a hard error or some other error.
I'm willing to make this change if this makes sense to you.
I'm trying to upload multiple images to my server and I'm doing the following:
After creating an MKNetworkOperation object (*op), I am then adding NSData converted UIImages to it:
[op addData: dataOne forKey:@"firstImage"]'
[op addData: dataTwo forKey:@"secondImage"];
My issue is the server never receives the second image, or the second object I should say. If I reverse the lines, "secondImage" is now received, not not first.
Can you clarify how to add multiple images to one POST? Thanks.
Hi,
I like to use the PSFoundation framework in my iOS apps. (https://github.com/steipete/PSFoundation)
It contains a lot of useful functions/categories/macros which make the app development much easier.
Now, I also want to use your awesome network framework (in exchange for ASIHTTP), but I can't compile my app
due to redefinitions in Reachabilty.h (Reachabilty exists in PSFoundation AND in MKNetworkKit).
The both files have a lot of differences, so I don't know which file I should take? Also a problem is if I remove the Reachablity code from one of the both frameworks, then I have to do this again and again, if there is a code update for this framework. And the two frameworks are then dependent on each other. Not nice ;-)
Any idea? Perhaps prefixing all enum, function, class names in Reachabilty.h/.m with TM (for Tony Million)?
Best regards,
Mario Sansone
Sadly NSHTTPRequest doesn't return the gzip encoded NSData, there is no way to know how much data you received when fetching gzip encoded content.
http://stackoverflow.com/questions/3413774/how-do-i-track-the-download-progress-of-gzip-encoded-web-content says ASIHTTPRequest dig into CFNetwork to be able to give you a download progress status. Right now the only solution is disabling gzip completely, which is bad for iOS apps.
Any plan to be able to fix this progress download for gzip encoded content?
4 ms, reading from memory.
For smooth scrolling using table view need additional cache layer in UI.
NSURL* originalURL = [NSURL URLWithString:((Asset*)assetNode).thumbnail_url];
[networkEngine imageAtURL:originalURL
onCompletion:^(UIImage *fetchedImage, NSURL *fetchedURL, BOOL isInCache) {
if(originalURL == fetchedURL)
[button setBackgroundImage:fetchedImage forState:UIControlStateNormal];
}];
// [button setBackgroundImage:[assetNode thumbnail] forState:UIControlStateNormal];
CFAbsoluteTime stopTime = CFAbsoluteTimeGetCurrent();
CFAbsoluteTime delta = startTime - stopTime;
NSLog(@"DELTA = %f",delta);
It seems there is no way to customize a MKNetworkOperation request timeout. As far as I can see, it is hard coded to 30s but in some cases it is not sufficient. I understand your comment below, and you're probably right, but sometimes your client web service has some wakeup time that will require more than 30 second for the first replies. According to me this timeout should be easily customizable without the need to set the "Request-Timeout" header explicitly.
// if your server takes longer than 30 seconds to provide real data,
// you should hire a better server developer.
// on iOS (or any mobile device), 30 seconds is already considered high.
I used RestKit with Cookie is working fine. When I try to use with MKNetworkKit , cookie is not working.
I use
NSArray* cookies=[loginModel setCookie];
for(NSHTTPCookie * cookie in cookies) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}
+(NSArray*)setCookie {
NSString* html=[[NSUserDefaults standardUserDefaults] objectForKey:@"cookie"];
NSArray * items = [html componentsSeparatedByString:@"\n"];
NSMutableArray* cookies = [[NSMutableArray alloc] init];
NSArray * parts;
NSString * cName;
NSString * cValue;
for(NSString * c in items) {
parts = [c componentsSeparatedByString:@"="];
if([parts count] == 2) {
cName = [parts objectAtIndex:0];
cValue = [parts objectAtIndex:1];
NSMutableDictionary * cookieProperties = [[NSMutableDictionary alloc] init];
[cookieProperties setValue:cName forKey:NSHTTPCookieName];
[cookieProperties setValue:cValue forKey:NSHTTPCookieValue];
[cookieProperties setValue:@"/" forKey:NSHTTPCookiePath];
[cookieProperties setValue:@".google.com" forKey:NSHTTPCookieDomain];
NSHTTPCookie * cookie = [[NSHTTPCookie alloc] initWithProperties:cookieProperties];
[cookies addObject:cookie];
[cookie release], cookie = nil;
[cookieProperties release], cookieProperties = nil;
}
} // end for
return cookies;
}
When accessing a url that is password protected i was successfully able to reach the site but then received a reachabilityChanged notification that said the site wasn't reachable. If I added a index file there was no reachabilityChanged notification.
2011-12-24 16:33:29.828 Practice[21131:fb03] -[MKNetworkEngine initWithHostName:customHeaderFields:] [Line 91] Engine initialized with host: localhost/~robert
2011-12-24 16:33:29.839 Practice[21131:fb03] -[MKNetworkOperation start] [Line 754] Saturday, December 24, 2011 4:33:29 PM Central Standard Time
Request
curl -X GET -H "Accept-Language: en, fr, de, ja, nl, it, es, pt, pt-PT, da, fi, nb, sv, ko, zh-Hans, zh-Hant, ru, pl, tr, uk, ar, hr, cs, el, he, ro, sk, th, id, ms, en-GB, ca, hu, vi, en-us" "http://localhost/~robert/pratice"
2011-12-24 16:33:29.980 Practice[21131:fb03] -[MKNetworkOperation connection:willSendRequest:redirectResponse:] [Line 1017] Redirected to http://localhost/~robert/pratice/
2011-12-24 16:33:29.989 Practice[21131:fb03] -[MKNetworkOperation operationSucceeded] [Line 1125] Saturday, December 24, 2011 4:33:29 PM Central Standard Time
Request
-------
curl -X GET -H "Accept-Language: en, fr, de, ja, nl, it, es, pt, pt-PT, da, fi, nb, sv, ko, zh-Hans, zh-Hant, ru, pl, tr, uk, ar, hr, cs, el, he, ro, sk, th, id, ms, en-GB, ca, hu, vi, en-us" "http://localhost/~robert/pratice"
--------
Response
--------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<title>Index of /~robert/pratice</title>
</head>
<body>
<h1>Index of /~robert/pratice</h1>
<table><tr><th><img src="/icons/blank.gif" alt="[ICO]"></th><th><a href="?C=N;O=D">Name</a></th><th><a href="? C=M;O=A">Last modified</a></th><th><a href="?C=S;O=A">Size</a></th><th><a href="?C=D;O=A">Description</a> </th></tr><tr><th colspan="5"><hr></th></tr>
<tr><td valign="top"><img src="/icons/back.gif" alt="[DIR]"></td><td><a href="/~robert/">Parent Directory</a> </td><td> </td><td align="right"> - </td><td> </td></tr>
<tr><th colspan="5"><hr></th></tr>
</table>
<address>Apache/2.2.20 (Unix) DAV/2 PHP/5.3.6 with Suhosin-Patch Server at localhost Port 80</address>
</body></html>
2011-12-24 16:33:29.990 Practice[21131:fb03] Success
2011-12-24 16:33:30.836 Practice[21131:11903] Reachability: -- -------
2011-12-24 16:33:30.836 Practice[21131:fb03] -[MKNetworkEngine reachabilityChanged:] [Line 168] Server [localhost/~robert] is not reachable
When resuming a download using the Range header, the Progress value indicates progress on the remaining ammount, not taking into account the resumed file size.
I.E. 1MB file resumed at 500k reports progress starting at 0% instead of 50%
It would make sense for me to take the entire size into account. Those who want the current behaviour could work backwards from the information returned. I envision returning currentPostion and expectedContentLength, calculating currentposition by data size + Range header value. Does this make sense? If so, i could just submit a pull request
At the end of MKNetworkOperation's main method I am printing the curl command for the requests. When pasted into terminal the requests works perfect. However printing other properties are showing that the params aren't being added to the body.
I'm running PHP scripts on a nginx server hosted by phpfog. I am determining the HTTP method with $_SERVER['REQUEST_METHOD'], and getting values with $_POST['key'].
I'm going to work on this on my fork, but if anyone has any brilliant idea's on how we can fix this it would be much appreciated.
Thanks for any help in advance.
Hi
i have the following piece of code that requests a page parses a table and extracts an element from the table, also that element has a url that needs to be queried to get an image, so the code has 2 operations one inside the other but the problem is that i get a lot of empty responses i dont know why and i dont think it's from the server because when i debug it and see the if body1==nil there in the headers it says content length > 0
here is the code
MKNetworkOperation *op = [self operationWithURLString:url params:fields];
[op onCompletion:^(MKNetworkOperation *operation) {
HTMLParser *parser = [[HTMLParser alloc] initWithString:op.responseString error:nil];
HTMLNode *body = [parser body];
HTMLNode *dataTable = [body findChildWithAttribute:@"class" matchingName:@"striped full" allowPartial:YES];
NSArray *rows = [dataTable findChildTags:@"tr"];
for (HTMLNode *trNode in rows) {
NSArray *cells = [trNode findChildTags:@"td"];
if(cells != nil && [cells count] > 0) {
Image *image = [[Image alloc] init];
HTMLNode *urlEl = [nameEl findChildTag:@"a"];
NSString *imageDetailsUrl = [urlEl getAttributeNamed:@"href"];
MKNetworkOperation *op1 = [self operationWithURLString:[host stringByAppendingString:imageDetailsUrl] params:nil];
[op1 onCompletion:^(MKNetworkOperation *operation1) {
HTMLParser *parser1 = [[HTMLParser alloc] initWithString:[op1 responseString] error:nil];
HTMLNode *body1 = [parser1 body];
NSLog(@"%lu", [[op1 responseString] length]);
if (body1 == nil) {
NSLog(@"nil.....");
NSDictionary *a = [[operation1 readonlyResponse] allHeaderFields];
}
HTMLNode *imageEl = [body1 findChildWithAttribute:@"id" matchingName:@"imagedetail_main_image" allowPartial:YES];
image.url = [imageEl getAttributeNamed:@"src"];
completionBlock(images);
} onError:^(NSError *error) {
DLog(@"%@", error);
}];
[images addObject:image];
[self enqueueOperation:op1];
}
}
completionBlock(images);
} onError:^(NSError *error) {
DLog(@"%@", error);
}];
[self enqueueOperation:op];
thanks
Hi Mugunth,
Will you consider writing/maintaining unit tests for this framework? There seems to be a critical lack of error handling throughout and thus zero tests to exercise said handling.
In the demo, the image upload doesn't resume after a connection break even though it has the [op setFreezable:YES] applied.
The log shows that the re-connect play has been pushed, but nothing seem to happen - Any ideas?
I prefer to explain my problem before: on an app that I'm working on I agreed with the web service developer the following two simple rules:
Unfortunately this 2nd approach is not feasible with MKNetworkKit, as the cached data will be reused but later a new network access will be run again. This requires a lot of unneeded network operations while most of the resources need to be downloaded once only.
My first idea would be to replace the "forceReload" argument with a "cache policy" one with the following states:
Or is there a better way to work with this?
Thank you
Carlo
It seems that if you try to run the jsonResponse method when the operation data is taken from cache, an exception is raised by the json serializer. In such case the only way to avoid this crash is to check if the answer is coming from cache or not and then in that use use responseData to get the json.
Probably the reason is coming from the fact that jsonResponse is accessing mutableData which is not affected when the response is retrieved directly from cache.
hi
im having problems with the cache it's always returning the page from the cache even the page changed meanwhile
http headers for the page are the following:
Cache-Control no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection keep-alive
Content-Encoding gzip
Content-Length 11690
Content-Type text/html; charset=utf-8
Date Tue, 21 Feb 2012 13:56:11 GMT
Expires Mon, 26 Jul 1997 05:00:00 GMT
Last-Modified Tue, 21 Feb 2012 13:56:06 GMT
P3P CP="OTI DSP COR ADM DEV PSA PSD IVDi OUR PUBi IND PRE"
Pragma no-cache
Server Apache
Set-Cookie MemberHash=3537509d5bcc59717ad5e1a88c38f90894d67adf; expires=Wed, 20-Feb-2013 13:56:06 GMT;
Vary Accept-Encoding
X-Cnection close
[operation isCachedResponse] always returns true
When looking at MKNetworkOperation API (header files), I cannot find a way to set postDataEncoding before initWithURLString gets called. The problem is that initWithURLString contains switch (self.postDataEncoding), which I would like to go to case MKNKPostDataEncodingTypeJSON.
My quick fix was to hardocode self.postDataEncoding = MKNKPostDataEncodingTypeJSON; which obviously is not a correct solution.
I think I'm missing something obvious...
Hi,
I took your demo, subclass the MKNetworkEngine and wrote some methods which hides all the network handling. So the consumer of my engine methods doesn't know anything about MKNetworkOperation.
Now, I want to stop all operations in the shared network queue, when the view will disappear (viewWillDisappear).
How can I do this?
I had the idea to add a "cancelAllOperations" method into my engine subclass, but from there I have no access to
_sharedNetworkQueue of MKNetworkEngine?
Do you think it would be a good idea to add the following method to MKNetworkEngine?
- (void)cancelAllOperations
{
for (MKNetworkOperation *operation in _sharedNetworkQueue.operations) {
[operation cancel];
}
}
Best regards,
Mario Sansone
If I am reading the source correctly, you are checking for reachability in the init method on the main thread: https://github.com/MugunthKumar/MKNetworkKit/blob/master/MKNetworkKit/MKNetworkEngine.m#L93
This should not be done, since it might lock up the application if there is no or hardly network available, and cause the app to be killed by the watchdog.
As Apple reminded lots of times in its sessions in all past WWDCs, reachability should only be used after a connection failed and not before connecting. Also it should never be done in the main thread on startup.
P.S.: I saw other developers doing this and having loads of problems, including crashes on startup, due to the watchdog coming up.
MKNetworkKit spits out far too much to the console for my liking. Please let us turn this off somehow.
Any way to force clear the cache, both in memory and disk?
I am trying to use the LinkedIn REST API with MkNetworkKit via RSOAuthEngine. I had to override the bodyData method in MKNetworkOperation to basically just use my XML document's NSData (not multi-part), and then in start check to see if I'm using my own XML data.
Does that make sense? Sorry it's been a long day.
I have set kMKNetworkKitRequestTimeOutInSeconds to be 1 second and I have simulated a server timeout of 60 seconds but I am never getting any sort of network error. How are timeouts handled with MKNetworkKit?
I'm trying to download big files with MKNetworkOperation. All downloading data is stored in mutableData field. Of course it crashes on device with 500Mb file.
If i comment creating mutableData and it is always nil - everything is working (maybe except progress).
I think there are should be option - store data in memory or not. Or my using of framework is wrong?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.