4

since NSURLConnection has been deprecated in iOS 9, I've attempting covering my code into NSURLSession but no success. Here is my old code:

class Book: NSObject {

    var pfBook : PFObject
    var coverImage : UIImage!

    init(pfBook: PFObject) {
        self.pfBook = pfBook
    }

    func fetchCoverImage(completion: (image: UIImage?, error: NSError?) -> Void) {
        let urlString = self.pfBook["s3thumbnailUrl"] as! String
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        let queue = dispatch_get_main_queue()

        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response: NSURLResponse?, data: NSData?, error: NSError?) in
            if error == nil {
                dispatch_async(dispatch_get_main_queue()){
                self.coverImage = UIImage(data: data!)
                completion(image: self.coverImage, error: nil)
                }
            } else {
                completion(image: nil, error: error)
            }
        }
    }
}

here's the new NSURLSession I attempted:

class Book: NSObject {

    var pfBook : PFObject
    var coverImage : UIImage!

    init(pfBook: PFObject) {
        self.pfBook = pfBook
    }

    func fetchCoverImage(completion: (image: UIImage?, error: NSError?) -> Void) {
        let urlString = self.pfBook["s3thumbnailUrl"] as! String
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        let session = NSURLSession.sharedSession()

        let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
            if error == nil {
                dispatch_async(dispatch_get_main_queue()){
                    self.coverImage = UIImage(data: data!)
                    completion(image: self.coverImage, error: nil)
                }
            }else {
                completion(image: nil, error: error)
            }

        })

        task.resume()
    }
}

When I run the app, my debugger is just spewing out errors, like so:

`2015-09-17 03:05:15.270 MyApp[562:59901] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802)
2015-09-17 03:05:15.331 My App[562:59936] This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes.  This will cause an exception in a future release.
 Stack:(
    0   CoreFoundation                      0x0000000183da4f74 <redacted> + 148
    1   libobjc.A.dylib                     0x0000000198997f80 objc_exception_throw + 56
    2   CoreFoundation                      0x0000000183da4ea4 <redacted> + 0
    3   Foundation                          0x0000000184dbe5d8 <redacted> + 88
    4   Foundation                          0x0000000184c40a1c <redacted> + 36
    5   UIKit                               0x00000001893ff958 <redacted> + 64
    6   UIKit                               0x00000001893ffb9c <redacted> + 548
    7   UIKit                               0x00000001893ff968 <redacted> + 80
    8   UIKit                               0x00000001892f62d8 <redacted> + 240
    9   UIKit                               0x000000018943f35c <redacted> + 640
    10  UIKit                               0x00000001893fc79c <redacted> + 144
    11  UIKit                               0x00000001893fc79c <redacted> + 144
    12  UIKit                               0x00000001893fc6d4 <redacted> + 68
    13  UIKit                               0x00000001893fc228 <redacted> + 120
    14  UIKit                               0x00000001893fc194 <redacted> + 280
    15  UIKit                               0x0000000189400d68 <redacted> + 1048
    16  UIKit                               0x00000001893fcc3c <redacted> + 244
    17  UIKit                               0x0000000189b25e8c <redacted> + 460
    18  UIKit                               0x0000000189b260f4 <redacted> + 200
    19  UIKit                               0x0000000189b25dbc <redacted> + 252
    20  UIKit                               0x0000000189b260f4 <redacted> + 200
    21  UIKit                               0x0000000189b25dbc <redacted> + 252
    22  UIKit                               0x00000001893ff968 <redacted> + 80
    23  UIKit                               0x0000000189b260c8 <redacted> + 156
    24  UIKit                               0x000000018940083c <redacted> + 100
    25  UIKit                               0x00000001893ff968 <redacted> + 80
    26  UIKit                               0x0000000189400470 <redacted> + 244
    27  UIKit                               0x0000000189b2397c <redacted> + 352
    28  UIKit                               0x0000000189af0f24 <redacted> + 200
    29  UIKit                               0x0000000189aefdec <redacted> + 72
    30  UIKit                               0x0000000189aefd88 <redacted> + 48
    31  UIKit                               0x0000000189ad6cf4 <redacted> + 104
    32  UIKit                               0x0000000189ad7264 <redacted> + 1108
    33  UIKit                               0x0000000189ae26f4 <redacted> + 436
    34  UIKit                               0x00000001894dd6f8 <redacted> + 4108
    35  UIKit                               0x0000000189ae4128 <redacted> + 132
    36  UIKit                               0x0000000189309dc0 <redacted> + 80
    37  UIKit                               0x0000000189ae3830 <redacted> + 2656
    38  UIKit                               0x0000000189ae1af8 <redacted> + 12448
    39  UIKit                               0x00000001894d87d8 <redacted> + 364
    40  MyApp                   0x0000000100101934 _TFFC17MyApp29ThirdCollectionViewController14collectionViewFS0_FTCSo16UICollectionView22cellForItemAtIndexPathCSo11NSIndexPath_CSo20UICollectionViewCellU_FTGSqCSo7UIImage_GSqCSo7NSError__T_ + 316
    41  MyApp                   0x00000001000b25fc`
`_TFFC17MyApp4Book15fetchCoverImageFS0_FFT5imageGSqCSo7UIImage_5errorGSqCSo7NSError__T_T_U_FTGSqCSo6NSData_GSqCSo13NSURLResponse_GSqS2___T_ + 580

    2015-09-17 03:05:15.353 MyApp[562:59936] This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes.  This will cause an exception in a future release.

what should I adjust?

adolfosrs
  • 9,286
  • 5
  • 39
  • 67
John Durand
  • 1,934
  • 5
  • 22
  • 34

4 Answers4

4

First of all i would like to mention few things that,

NSURLConnection is deprecated in OS X 10.11 and iOS 9.0 but:

  • Not going away, apps using it will still work

  • New features will be added to NSURLSession

  • Not supported on watchOS

Secondly,

Using NSURLSession and sending async call with it is as easy as with NSURLConnection.

This is a sample code to send an async request. Hope it helps.

NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:londonWeatherUrl]
          completionHandler:^(NSData *data,
                              NSURLResponse *response,
                              NSError *error) {
            // handle response

  }] resume]; 

dataTaskWithURL is intended to replace sendAsynchronousRequest in NSURLConnection.

Midhun MP
  • 103,496
  • 31
  • 153
  • 200
Usama
  • 548
  • 3
  • 12
1

with swift3,

let liveInfoUrl = URL(string: "http://192.168.1.66/api/cloud/app/liveInfo/7777")
let task = URLSession.shared.dataTask(with: liveInfoUrl! as URL) {data, response, error in
    guard let data = data, error == nil else { return }
    print(String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) ?? "aaaa")
}
task.resume()
LF00
  • 27,015
  • 29
  • 156
  • 295
0

function below is working fine for me.

func fetchCoverImage(completion: (image: UIImage?, error: NSError?) -> Void) {

    //        let url = NSURL(string: urlString)
    var request = NSMutableURLRequest(URL: NSURL(string: "http://www.fnordware.com/superpng/pnggrad16rgb.png")!)
    let session = NSURLSession.sharedSession()

    let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        if error == nil {
            dispatch_async(dispatch_get_main_queue()){
                self.coverImage?.image = UIImage(data: data!)
                completion(image: self.coverImage?.image, error: nil)
            }
        }else {
            completion(image: nil, error: error)
        }

    })

    task.resume()
}   

}

Let me know if you face any issue using this. I just changed the url to some png image.

Usama
  • 548
  • 3
  • 12
  • would you mind entering [this chat](http://chat.stackoverflow.com/rooms/89883/ios-9-conversion) for a very brief moment? – John Durand Sep 17 '15 at 07:38
0

There's probably nothing wrong with your code. NSURLConnection will do the same thing if you compile against the iOS 9 SDK. You're running into App Transport Security restrictions. Read about it here:

https://developer.apple.com/library/prerelease/ios/technotes/App-Transport-Security-Technote/

Basically, if you want to access URLs without strong encryption, you have to modify your Info.plist file to tell iOS to let you do do.

dgatwood
  • 10,129
  • 1
  • 28
  • 49