Code Monkey home page Code Monkey logo

mknetworkkit's Introduction

This is version 2.0 of MKNetworkKit. Version 2 is based on NSURLSession and NSURLConfiguration.

Version 1.x of MKNetworkKit is deprecated as NSURLConnection is deprecated in iOS 9 and is not available on tvOS.

A Swift version is available [here] (https://github.com/MugunthKumar/MKNetworkKit-Swift)

###Why MKNetworkKit?

  • Single network queue for the whole app
  • Auto queue sizing and auto network indicator support
  • High performance background caching (based on HTTP 1.1 caching specs) built in
  • You don't need a separate image cache library
  • Background image decompression
  • Background completion
  • cURL-able debug lines

These are just a few of most interesting features on MKNetworkKit.

###Installation Drag the MKNetworkKit directory to your project. We will be supporting Carthage soon and have a demo app setup, so you can test the features.

###How to use WIP.

###Licensing

MKNetworkKit is licensed under MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


###Attribution free licensing In case you need attribution free licensing for MKNetworkKit, you can buy one from my license store.


Documentation

Install appledoc from gentlebytes github repo run this on the command line /usr/local/bin/appledoc --project-name MKNetworkKit -v 0.8 --project-company Steinlogic --company-id com.steinlogic.mknetworkkit -o ./Documentation -i .m -s ./MKNetworkKit .

####AppleDoc License appledoc is licensed with modified BSD license. In plain language: you're allowed to do whatever you wish with the code, modify, redistribute, embed in your products (free or commercial), but you must include copyright, terms of usage and disclaimer as stated in the license, the same way as any other BSD licensed code. You can of course use documentation generated by appledoc for your products (free or commercial), but you must attribute appledoc either in documentation itself or other appropriate place such as your website.

If for whatever reason you cannot agree to these terms, contact us through contact form on our about page, we'll do our best to help you out you out and find a workable solution!

Copyright (c) 2009-2011, Gentle Bytes All rights reserved.

Redistribution and use in source, binary forms and generated documentation, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

Redistributions of documentation generated by appledoc must include attribution to appledoc, either in documentation itself or other appropriate media.

Neither the name of the appledoc, Gentle Bytes nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Gentle Bytes [email protected]


###TODO

  • Operation coaleasing
  • OAuth/client certificate support
  • Add local notification support
  • MKObject data transformers

mknetworkkit's People

Contributors

3van avatar blazingpair avatar bo98 avatar brandonemrich avatar hout avatar insanehunter avatar jgimenez avatar juliengrimault avatar maxcanna avatar michaelroling avatar milancermak avatar mugunthkumar avatar nvkv avatar penso avatar rileytestut avatar rsieiro avatar teeqemm avatar thomasclaysonpowa avatar vbgoz avatar yas375 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mknetworkkit's Issues

unit testing issue

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?

How to support "cache only" behavior?

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:

  1. all "dynamic" requests will be run, and if the app is offline the cached data will be reused: this approach is perfectly done using MKNetworkKit cache management
  2. all "static resources" should be downloaded from the network only if not cached yet; if they're cached they must be used and no re-download from the network is needed; this approach is safe because the agreement with the web service developer is such that if a specific resource must be changed (e.g. the photo of a particular item) its URL will change and in this case we would have a "cache fault" which will require network download.

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:

  1. don't use cache
  2. use cache and then reload
  3. reload only if no cache
    But probably it is better to move this as a network engine parameter (global setting) and operation parameter (local setting), something similar is already done by ASIHTTPRequest.

Or is there a better way to work with this?

Thank you

Carlo

jsonResponse not working for cached data

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.

Flickr example showing wrong images

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.

Cache management

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.

NSHTTPCookieStorage with MKNetworkKit

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;
}

Read-only property to get HTTP Method from MKNetworkOperation

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!

Get redirectURL

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

Raw binary data in Request Body

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?

The definition of ELog macro is dangerous!

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)

To Big read time from memory cache

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);

Feature request: allow for non-multipart POST of XML data

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.

Handling network timeouts

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?

Lack of unit tests and error handling

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.

Memory Leaks in NSString+MKNetworkKitAdditions.m

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
    }

response issue

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

Authentication cached somewhere

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.

Post params not being sent with data if not on WiFI

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.

about post body

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~

Download progress indicator does not reflect total progress when resuming download

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

Download Progress for gzip encoded content

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?

Cache issues

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

HTTP Digest Authentication: providing wrong username&pw => endless loop op:connection:willSendRequestForAuthenticationChallenge

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

Huge memory usage on big files

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?

MKNetworkOperation connectionDidFinishLoading and 401

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.

Enqueuing operations can crash if operation is cancelled on another thread before completion

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.

Cache Behavior

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.

Image upload not resuming...

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?

saveCacheData iOS 4.3 crash

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)

Reachability check on init

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.

JSON Encoding yields application/x-www-form-urlencoded Content-Type

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.

Doesn't compile together with PSFoundation framework

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

Help, enqueueOperation method throw an exception

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?

Should POST Content-Type application/x-www-form-urlencoded include charset?

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?

POST Request with empty body crashes

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.

POST request variables not added to body

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.

Possible reachability corner case...

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>&nbsp;</td><td align="right">  - </td><td>&nbsp;</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

Upload gzip data

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

Request timeout is not customizable

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.

How to set postDataEncoding before initWithURLString

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...

Cancel all operations in sharedNetworkQueue

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

MKNetworkOperation addData

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.