• Stars
    star
    113
  • Rank 310,115 (Top 7 %)
  • Language
    Objective-C
  • License
    MIT License
  • Created over 9 years ago
  • Updated almost 8 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A `NSOperation` subclass for requests added to `AFHTTPSessionManager`

AFHTTPSessionOperation

Introduction

AFHTTPSessionOperation is a NSOperation subclass for HTTP requests added to AFNetworking's AFHTTPSessionManager. AFURLSessionOperation is a NSOperation subclass for data, upload, and download requests implemented in AFURLSessionManager.

This has been updated for AFNetworking 3.x. See 2.x branch of this repo if you're using AFNetworking 2.x.

When using AFHTTPRequestOperationManager (now retired), you enjoy NSOperation capabilities, but when using AFHTTPSessionManager, you don't. This is somewhat understandable (as NSURLSession introduces background requests, and that's incompatible with NSOperation-based approaches), but when performing requests in the foreground, it's useful to have NSOperation-style capabilities. This class makes that possible.

Usage

AFHTTPSessionOperation

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFImageResponseSerializer serializer];

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
queue.maxConcurrentOperationCount = 3;

NSArray *filenames = @[@"file1.jpg", @"file2.jpg", @"file3.jpg", @"file4.jpg", @"file5.jpg", @"file6.jpg"];

for (NSString *filename in filenames)  {
    NSString *urlString = [@"http://example.com" stringByAppendingPathComponent:filename];
    NSOperation *operation = [AFHTTPSessionOperation operationWithManager:manager HTTPMethod:@"GET" URLString:urlString parameters:nil uploadProgress:nil downloadProgress:^(NSProgress *downloadProgress) {
        NSLog(@"%@: %.1f", filename, downloadProgress.fractionCompleted * 100.0);
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@: %@", filename, NSStringFromCGSize([responseObject size]));
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@: %@", filename, error.localizedDescription);
    }];
    [queue addOperation:operation];
}

AFURLSessionOperation

AFURLSessionManager *manager = [[AFURLSessionManager alloc] init];

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
queue.maxConcurrentOperationCount = 3;

NSArray *filenames = @[@"file1.jpg", @"file2.jpg", @"file3.jpg", @"file4.jpg", @"file5.jpg", @"file6.jpg"];

for (NSString *filename in filenames)  {
    NSString *urlString = [@"http://example.com" stringByAppendingPathComponent:filename];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];

    NSOperation *operation = [AFURLSessionOperation downloadOperationWithManager:manager request:request progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"%@: %.1f", filename, downloadProgress.fractionCompleted * 100.0);
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        NSError *error;
        NSURL *documentsURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:false error:&error];
        return [documentsURL URLByAppendingPathComponent:filename];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        NSLog(@"%@ done %@", filename, (error.localizedDescription ?: @""));
    }];
    [queue addOperation:operation];
}

Progress and completion

The progress of a series of requests can be accomplished by creating your own NSProgress object and then call addChild for the NSProgress objects of all of the tasks that are created. You can then add an observer to the fractionCompleted of your NSProgress.

To determine when the downloads are done, you can add an operation (e.g. a NSBlockOperation) and then make it dependent upon all of the other operations that were added to the queue.

To illustrate this, a Swift 2 implementation might look like so. The Objective-C implementation is equivalent.

import UIKit

private var observerContext = 0

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        progress = NSProgress()
        progress.addObserver(self, forKeyPath: "fractionCompleted", options: .New, context: &observerContext)

        downloadFiles()
    }

    private var progress: NSProgress!

    deinit {
        progress?.removeObserver(self, forKeyPath: "fractionCompleted")
    }

    private func downloadFiles() {
        let filenames = ["as17-134-20380.jpg", "as17-140-21497.jpg", "as17-148-22727.jpg"]

        let baseURL = NSURL(string: "http://example.com/path")!

        let queue = NSOperationQueue()
        queue.maxConcurrentOperationCount = 4

        progress.totalUnitCount = Int64(filenames.count)
        progress.completedUnitCount = 0

        let manager = AFHTTPSessionManager()
        manager.responseSerializer = AFImageResponseSerializer()

        let completionOperation = NSBlockOperation {
            print("done")
        }

        for filename in filenames {
            let url = baseURL.URLByAppendingPathComponent(filename)
            let operation = AFHTTPSessionOperation(manager: manager, HTTPMethod: "GET", URLString: url.absoluteString, parameters: nil, uploadProgress: nil, downloadProgress: nil, success:
                { (task, responseObject) -> Void in
                    print("\(filename): \(NSStringFromCGSize((responseObject as! UIImage).size))")
                }, failure: { task, error in
                    print("\(filename): \(error)")
                })
            queue.addOperation(operation)
            completionOperation.addDependency(operation)
            progress.addChild(manager.downloadProgressForTask(operation.task!)!, withPendingUnitCount: 1)
        }

        queue.addOperation(completionOperation)
    }

    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if context == &observerContext {
            if keyPath == "fractionCompleted" {
                let percent = change![NSKeyValueChangeNewKey] as! Double
                print("\(percent)")
            }
        } else {
            super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
        }
    }

}

Note, this is a mix and match situation, where you can use either NSProgress or completion handler or both or neither. I just depends upon your needs.

Reference

As contemplated in AFNetworking issue #1504.

License

The MIT License (MIT)

Copyright (c) 2015 Rob Ryan

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.

More Repositories

1

CustomMapViewAnnotationCalloutSwift

Custom iOS MapView Annotation Callouts in Swift
Swift
82
star
2

download-manager

NSURLConnection Download Manager
Objective-C
81
star
3

Interactive-Custom-Transitions-in-Swift

This illustrates one fairly narrow example of interactive custom transitions in Swift
Swift
48
star
4

mapkit-animated-overlays

iOS MapKit Animated Overlays
Objective-C
37
star
5

NetworkManager

A NSOperation-based wrapper for delegate-based NSURLSession
Objective-C
32
star
6

SwiftCustomTransitions

Swift 3 Custom Transitions Demonstration
Swift
28
star
7

BGAppRefresh

Demo of iOS app refresh
Swift
26
star
8

NSURLSessionMultipart

Swift framework that extends `NSURLSession` to provide simple multipart/form-data requests
Swift
22
star
9

Operation-Test-Swift

Test of asynchronous `NSOperation` in Swift with appropriate KVO
Swift
16
star
10

CircularCollectionView

Swift `UICollectionView` with circle of cells
Swift
15
star
11

edge-swipe-demonstration

iOS demonstration of pan gesture navigation by swiping from edge of the screen
Objective-C
13
star
12

LazyTableImages

A revision of Apple's LazyTableImages that remedies some basic issues in their sample
Objective-C
13
star
13

ZipArchive

ZipArchive is an Objective-C class to compress or uncompress zip files, which is base on open source code "MiniZip".
C
11
star
14

PeoplePickerSwiftDemo

A Swift demonstration of ABPeoplePickerNavigationController
Swift
11
star
15

SimplePing

Update of Apple’s SimplePing for Swift 5
Objective-C
9
star
16

Custom-Annotation-With-DrawRect

This is an iOS example `MKAnnotationView` subclass with a custom `drawRect` implementation.
Objective-C
7
star
17

ios-wunderground-demo

iOS Wunderground Demo
Objective-C
7
star
18

AsyncAwaitBenchmarks

Swift
6
star
19

CircleMaskDemo

Swift 4 example of gestures controlling image mask
Swift
5
star
20

PeriodicTable

A demonstration of custom collection view layout to show the periodic table in iOS app
Swift
5
star
21

AnimateMasks

A demonstration of using UIPanGestureRecognizer to animate the changing of masks of image views
Objective-C
5
star
22

CoreText-Demonstration

Demonstration of CoreText and gestures
Objective-C
4
star
23

SQLiteDemo

This is demonstration based upon Medium article, Manage data in SQLite in iOS using Swift
Swift
3
star
24

iOS-XML-Streaming-w-Base64-Decode

iOS XML Streaming demonstration with Base64 decoding
Objective-C
3
star
25

SerialTaskDemo

Swift
3
star
26

CustomPointsOfInterest

Instruments tool for points of interest with custom colors (contcepts)
Swift
3
star
27

UITableView-Bottom-Refresh

iOS UITableView with pull up to refresh (i.e. bottom refresh)
Objective-C
3
star
28

PubNubClient

Demo of custom payload for PubNub events
Swift
3
star
29

ImageDownloadWithProgress

Objective-C demo of downloading images and updating image view
Objective-C
3
star
30

download-operation

An iOS operation class for downloading files from remote server
Objective-C
3
star
31

yahoo-weather-demonstration

A demonstration of an iOS app that requests information from the Yahoo! weather services
Objective-C
3
star
32

ArcView

https://stackoverflow.com/a/66189501/1271826
Swift
2
star
33

location-services-logging-test

This is a simple test of iOS significant change location service
Objective-C
2
star
34

Page-View-Controller-Swift-Demonstration

iOS Page View Controller Swift Demonstration
Swift
2
star
35

MKMapView-custom-annotations

MKMapView Custom Annotations
Objective-C
2
star
36

GeocoderTableView

iOS demonstration of showing distances to locations in a table view; see https://stackoverflow.com/q/65831084/1271826
Swift
2
star
37

MKCircle-MKPolygon-intersection

An illustration of how to detect intersection between iOS MKCircleView and MKPolygonView
Objective-C
2
star
38

PagingDemo

Example of paging through series of child view controllers
Swift
2
star
39

ColoredArcs

Objective-C demo updating CAShapeLayer arc colors based upon gesture
Objective-C
2
star
40

CustomNavigationAnimator

Swift custom interactive push transition
Swift
2
star
41

ASPLoginDemo

See http://stackoverflow.com/questions/40728386
Objective-C
2
star
42

MapKitClusteringObjC

iOS MapKit Clustering Demo in Objective-C
Objective-C
2
star
43

CircularArrowDemo

Objective-C Demo of creating `UIBezierPath` in the shape of a circular arrow
Objective-C
2
star
44

RefactoredViewController

Refactored View Controller from CodeReview question
Swift
2
star
45

RadioPlayer

This is an iOS Swift demonstration of using Key-Value Notification (KVN) to detect changes in `reasonForWaitingToPlay` of `AVPlayer`.
Swift
2
star
46

SerialTasks

https://stackoverflow.com/a/73072799/1271826
Swift
2
star
47

EmbeddedPageViewController

Example of embedding iOS page view controller within a scene with other controls on it
Swift
2
star
48

PointsAndLines

Sample iOS project that draws mesh of chart points and lines between them
Objective-C
2
star
49

ios-location-test

This is a rudimentary demonstration of the client-side code which uses iOS location services and JSON parsing to provide functionality similar to the Apple "Find My Friends"
Objective-C
2
star
50

ScreenEdgeGestureNavigationController

An iOS 7+ subclass of UINavigationController that provides a swipe from right edge to push to "next" view controller, as well as swipe from left edge to pop to previous view controller
Objective-C
2
star
51

CachedController

Cached View Controllers in Swift
Swift
1
star
52

SampleBridgingProject

SampleBridgingProject - Test of code completion when calling Swift code from Objective-C
Objective-C
1
star
53

DynamicAnnotations

Demonstrate the need for dynamic coordinates for MKAnnotation objects
Swift
1
star
54

PointsOfInterestDemo

Demonstration of bug in Points of Interest in Xcode 11.4
Swift
1
star
55

PolygonViewDemo

Example of Swift IBDesignable view that uses CAShapeLayer to draw a polygon
Swift
1
star
56

BoxDragger

Swift
1
star
57

ObjcSwiftFrameworkDemo

Example framework using Objective-C and Swift without any custom modulemap
Swift
1
star
58

autolayout-category

This is a category of iOS auto layout convenience methods
Objective-C
1
star
59

Breaches

Quick and dirty Swift demo of using MVP/MVVM patterns to pull business logic, network logic, etc. out of a view controller.
Swift
1
star
60

CollectionViewDemo

https://stackoverflow.com/questions/45107860/create-new-view-controller-upon-uicollectionviewcell-clicked
Swift
1
star
61

CollectionViewDemo2

https://stackoverflow.com/a/63083233/1271826
Swift
1
star
62

CountWhitePixels

https://stackoverflow.com/a/58513549/1271826
Swift
1
star
63

DateComponentsFormatterBug

DateComponentsFormatter formattingContext Bug
Swift
1
star
64

Mandelbrot

A macOS/iOS calculation of Mandelbrot set in Swift
Swift
1
star
65

containment-animation

Demonstration of animation in conjunction with view controller containment
Objective-C
1
star
66

ZipBrowser

This is Apple's ZipBrowser, updated for ARC
Objective-C
1
star
67

CLFloorBug

Manifest `CLLocationManager.location.floor` bug on iOS 13.3.1 physical devices
Swift
1
star
68

SampleFramework

SampleFramework
Objective-C
1
star
69

StateRestorationSimple

Simple example of state restoration (pre UIScene)
Swift
1
star
70

AddSubviewDemo

https://stackoverflow.com/questions/44816254/programmatically-create-an-array-of-objects-swift-3
Swift
1
star
71

Books

Swift
1
star
72

ConcaveCollision

Swift project illustrating concave collision path (through series of linear paths)
Swift
1
star
73

DogWalking

https://stackoverflow.com/a/55989901/1271826
Swift
1
star
74

MyApp

https://stackoverflow.com/q/72594694/1271826
Objective-C
1
star
75

TableSearchwithUISearchController

Apple's UISearchController demo from https://developer.apple.com/library/content/samplecode/TableSearch_UISearchController/Introduction/Intro.html
Objective-C
1
star
76

TickMarkCircleViewDemo

Tick Mark Circle View Demo in Swift
Swift
1
star
77

ViewContainerDemo

https://stackoverflow.com/questions/78050537/adding-two-uiview-vertically
Swift
1
star
78

ContactsMockup

Mockup of iOS Contacts App animation in Swift
Swift
1
star