Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 42 additions & 28 deletions Hacker Swifter/Hacker Swifter/HTTP/Fetcher.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ public class Fetcher {
internal let baseURL = "https://news.ycombinator.com/"
internal let APIURL = "https://hn.algolia.io/api/v1/"
private let session = NSURLSession.sharedSession()

private let reachability: Reachability?


public typealias FetchCompletion = (object: AnyObject!, error: ResponseError!, local: Bool) -> Void
public typealias FetchParsing = (html: String!) -> AnyObject!
Expand All @@ -26,49 +29,60 @@ public class Fetcher {
case ErrorParsing = "An error occurred while fetching the requested page"
case UnknownError = "An unknown error occurred"
}

public class var sharedInstance: Fetcher {
return _Fetcher
}

init() {
reachability = Reachability.reachabilityForInternetConnection()
reachability!.startNotifier()
}

private func hostReachable() -> Bool {
return (_Fetcher.reachability!.currentReachabilityStatus() == NetworkStatus.ReachableViaWiFi || _Fetcher.reachability!.currentReachabilityStatus() == NetworkStatus.ReachableViaWWAN)
}

class func Fetch(ressource: String, parsing: FetchParsing, completion: FetchCompletion) {

self.showLoadingIndicator(true)

var cacheKey = Cache.generateCacheKey(ressource)
Cache.sharedCache.objectForKey(cacheKey, completion: {(object: AnyObject!) in
if var realObject: AnyObject = object {
completion(object: realObject, error: nil, local: true)
}
})

var path = _Fetcher.baseURL + ressource
var task = _Fetcher.session.dataTaskWithURL(NSURL(string: path) , completionHandler: {(data: NSData!, response, error: NSError!) in
if !error {
if let realData = data {
var object: AnyObject! = parsing(html: NSString(data: realData, encoding: NSUTF8StringEncoding))
if var realObject: AnyObject = object {
Cache.sharedCache.setObject(realObject, key: cacheKey)
if (_Fetcher.hostReachable()) {
var path = _Fetcher.baseURL + ressource
var task = _Fetcher.session.dataTaskWithURL(NSURL(string: path) , completionHandler: {(data: NSData!, response, error: NSError!) in
if !error {
if let realData = data {
var object: AnyObject! = parsing(html: NSString(data: realData, encoding: NSUTF8StringEncoding))
if var realObject: AnyObject = object {
Cache.sharedCache.setObject(realObject, key: cacheKey)
}
dispatch_async(dispatch_get_main_queue(), { ()->() in
self.showLoadingIndicator(false)
completion(object: object, error: nil, local: false)
})
}
dispatch_async(dispatch_get_main_queue(), { ()->() in
self.showLoadingIndicator(false)
completion(object: object, error: nil, local: false)
else {
dispatch_async(dispatch_get_main_queue(), { ()->() in
self.showLoadingIndicator(false)
completion(object: nil, error: ResponseError.UnknownError, local: false)
})
}
}
else {
dispatch_async(dispatch_get_main_queue(), { ()->() in
self.showLoadingIndicator(false)
completion(object: nil, error: ResponseError.UnknownError, local: false)
})
completion(object: nil, error: ResponseError.UnknownError, local: false)
}
}
else {
completion(object: nil, error: ResponseError.UnknownError, local: false)
}
})
task.resume()
})
task.resume()
} else {
Cache.sharedCache.objectForKey(cacheKey, completion: {(object: AnyObject!) in
if var realObject: AnyObject = object {
completion(object: realObject, error: nil, local: true)
}
})
}
}

//In the future, all scraping will be removed and we'll use only the Algolia API
//At the moment this function is sufixed for testing purpose
class func FetchAPI(ressource: String, parsing: FetchParsingAPI, completion: FetchCompletion) {
Expand Down
5 changes: 5 additions & 0 deletions Hacker Swifter/Hacker Swifter/HackerSwifter-Bridging-Header.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//

#import "Reachability.h"
105 changes: 105 additions & 0 deletions Hacker Swifter/Hacker Swifter/Reachability.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/*
File: Reachability.h
Abstract: Basic demonstration of how to use the SystemConfiguration Reachablity APIs.
Version: 3.5

Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple
Inc. ("Apple") in consideration of your agreement to the following
terms, and your use, installation, modification or redistribution of
this Apple software constitutes acceptance of these terms. If you do
not agree with these terms, please do not use, install, modify or
redistribute this Apple software.

In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the
"Apple Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may
be used to endorse or promote products derived from the Apple Software
without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or
implied, are granted by Apple herein, including but not limited to any
patent rights that may be infringed by your derivative works or by other
works in which the Apple Software may be incorporated.

The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.

IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

Copyright (C) 2014 Apple Inc. All Rights Reserved.

*/

#import <Foundation/Foundation.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <netinet/in.h>


/*typedef enum : NSInteger {
NotReachable = 0,
ReachableViaWiFi,
ReachableViaWWAN
} NetworkStatus;*/
typedef NS_ENUM(NSInteger, NetworkStatus) {
NotReachable = 0,
ReachableViaWiFi,
ReachableViaWWAN
};


extern NSString *kReachabilityChangedNotification;


@interface Reachability : NSObject

/*!
* Use to check the reachability of a given host name.
*/
+ (instancetype)reachabilityWithHostName:(NSString *)hostName;

/*!
* Use to check the reachability of a given IP address.
*/
+ (instancetype)reachabilityWithAddress:(const struct sockaddr_in *)hostAddress;

/*!
* Checks whether the default route is available. Should be used by applications that do not connect to a particular host.
*/
+ (instancetype)reachabilityForInternetConnection;

/*!
* Checks whether a local WiFi connection is available.
*/
+ (instancetype)reachabilityForLocalWiFi;

/*!
* Start listening for reachability notifications on the current run loop.
*/
- (BOOL)startNotifier;
- (void)stopNotifier;

- (NetworkStatus)currentReachabilityStatus;

/*!
* WWAN may be available, but not active until a connection has been established. WiFi may require a connection for VPN on Demand.
*/
- (BOOL)connectionRequired;

@end


Loading