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
2 changes: 1 addition & 1 deletion Sources/MBNetworking/Extensions/CharacterEncoding.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ extension CharacterSet {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
let encodableDelimiters = CharacterSet(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")

return CharacterSet.urlQueryAllowed.subtracting(encodableDelimiters)
}()
}
2 changes: 0 additions & 2 deletions Sources/MBNetworking/Extensions/Data.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,8 @@
import Foundation

extension NSMutableData {

func appendString(_ string: String) {
guard let data = string.data(using: .utf8) else { return }
append(data)
}

}
2 changes: 0 additions & 2 deletions Sources/MBNetworking/Extensions/ProcessInfo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,8 @@
import Foundation

extension ProcessInfo {

/// Returns true if process is in testing.
static var isUnderTest: Bool {
ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil
}

}
6 changes: 3 additions & 3 deletions Sources/MBNetworking/Extensions/SecTrust.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import Foundation

public extension Array where Element == SecCertificate {
public extension [SecCertificate] {
var publicKeys: [SecKey] {
compactMap(\.publicKey)
}
Expand All @@ -32,9 +32,9 @@ public extension SecCertificate {
public extension SecTrust {
var certificates: [SecCertificate] {
if #available(iOS 15, macOS 12, watchOS 8, *) {
return (SecTrustCopyCertificateChain(self) as? [SecCertificate]) ?? []
(SecTrustCopyCertificateChain(self) as? [SecCertificate]) ?? []
} else {
return (0 ..< SecTrustGetCertificateCount(self)).compactMap { index in
(0 ..< SecTrustGetCertificateCount(self)).compactMap { index in
SecTrustGetCertificateAtIndex(self, index)
}
}
Expand Down
12 changes: 5 additions & 7 deletions Sources/MBNetworking/Extensions/URL.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,24 @@

import Foundation

extension URL {

public extension URL {
/// Initializes URL with string. Same as URL(string:), but returns URL (not optional.)
/// In case of failure in initializing, fatal error will be thrown.
public init(forceString string: String) {
init(forceString string: String) {
guard let url = URL(string: string) else { fatalError("Could not init URL '\(string)'") }
self = url
}

/// Returns URL by settings URL.queryItems to specified parameters.
public func adding(parameters: [String: String]) -> URL {
func adding(parameters: [String: String]) -> URL {
guard parameters.count > 0 else { return self }
var queryItems: [URLQueryItem] = []
for parameter in parameters {
queryItems.append(URLQueryItem(name: parameter.key, value: parameter.value))
}
return adding(queryItems: queryItems)
}

/// Returns URL by settings URL.queryItems to specified queryItems.
private func adding(queryItems: [URLQueryItem]) -> URL {
guard var urlComponents = URLComponents(string: absoluteString) else {
Expand All @@ -38,5 +37,4 @@ extension URL {
}
return url
}

}
26 changes: 12 additions & 14 deletions Sources/MBNetworking/Networkable+DataTask.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//
// Network.swift
// Networkable+DataTask.swift
// Network
//
// Created by Rasid Ramazanov on 25.11.2019.
Expand All @@ -19,12 +19,11 @@ extension Networkable {
_ type: V.Type,
completion: @escaping ((Result<V, MBErrorKit.NetworkingError>) -> Void)
) {
fetch(request, completion: completion)

// StubURLProtocol enabled and adding a small delay.
if StubURLProtocol.isEnabled, ProcessInfo.isUnderTest {
fetch(request, completion: completion)
RunLoop.current.run(until: Date().addingTimeInterval(0.05))
} else {
fetch(request, completion: completion)
}
}

Expand All @@ -34,19 +33,18 @@ extension Networkable {
) {
requestData(urlRequest) { response, data, error in

if let error = error,
if let error,
self.isNetworkConnectionError((error as NSError).code) {
let error = MBErrorKit.NetworkingError.networkConnectionError(error)
MBErrorKit.ErrorKit.shared().delegate?.errorKitDidCatch(networkingError: error)
self.printErrorLog(error)
completion(.failure(error))

} else if let error = error {
let networkingError: NetworkingError
if (error as NSError).code == NSURLErrorCancelled {
networkingError = .dataTaskCancelled
} else if let error {
let networkingError: NetworkingError = if (error as NSError).code == NSURLErrorCancelled {
.dataTaskCancelled
} else {
networkingError = MBErrorKit.NetworkingError.underlyingError(error, response, data)
MBErrorKit.NetworkingError.underlyingError(error, response, data)
}
MBErrorKit.ErrorKit.shared().delegate?.errorKitDidCatch(networkingError: networkingError)
self.printErrorLog(networkingError)
Expand All @@ -59,13 +57,13 @@ extension Networkable {
self.printErrorLog(error)
completion(.failure(error))

} else if let response = response, data == nil || data?.count == 0 {
} else if let response, data == nil || data?.count == 0 {
let error = MBErrorKit.NetworkingError.dataTaskError(response, data)
MBErrorKit.ErrorKit.shared().delegate?.errorKitDidCatch(networkingError: error)
self.printErrorLog(error)
completion(.failure(error))

} else if let data = data, data.count > 0 {
} else if let data, !data.isEmpty {
do {
// If requested decodable type is Data, received data will be returned.
if V.Type.self == Data.Type.self {
Expand Down Expand Up @@ -111,9 +109,9 @@ extension Networkable {
}
Session.shared.networkLogMonitoringDelegate?.logTask(task: task, didCompleteWithError: error)
}

Session.shared.tasksInProgress.removeValue(forKey: taskId)

self.printResponse(data)
DispatchQueue.main.async {
completion(response, data, error)
Expand Down
90 changes: 90 additions & 0 deletions Sources/MBNetworking/Networkable+DataTaskAsync.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
//
// Networkable+DataTaskAsync.swift
// Network
//
// Created by Rasid Ramazanov on 25.11.2019.
// Copyright © 2019 LeanScale. All rights reserved.
//

import Foundation
import MBErrorKit

/// Networkable extension related to data tasks.
///
@available(iOS 13.0.0, *) extension Networkable {
/// Fetch data with specified parameters and return back with the completion.
/// - Parameters:
/// - type: Type of the result.
/// - Returns: Response as `Result`
public func fetch<V: Decodable>(_ type: V.Type) async throws -> V {
try await fetch(request)
}

private func fetch<V: Decodable>(_ urlRequest: URLRequest) async throws -> V {
let (response, data, error) = await requestData(urlRequest)

if let error,
isNetworkConnectionError((error as NSError).code) {
let error = MBErrorKit.NetworkingError.networkConnectionError(error)
MBErrorKit.ErrorKit.shared().delegate?.errorKitDidCatch(networkingError: error)
printErrorLog(error)
throw error

} else if let error {
let networkingError: NetworkingError = if (error as NSError).code == NSURLErrorCancelled {
.dataTaskCancelled
} else {
MBErrorKit.NetworkingError.underlyingError(error, response, data)
}
MBErrorKit.ErrorKit.shared().delegate?.errorKitDidCatch(networkingError: networkingError)
printErrorLog(networkingError)
throw networkingError

} else if let httpResponse = response as? HTTPURLResponse,
isSuccess(httpResponse.statusCode) {
let error = MBErrorKit.NetworkingError.httpError(error, httpResponse, data)
MBErrorKit.ErrorKit.shared().delegate?.errorKitDidCatch(networkingError: error)
printErrorLog(error)
throw error

} else if let response, data == nil || data?.count == 0 {
let error = MBErrorKit.NetworkingError.dataTaskError(response, data)
MBErrorKit.ErrorKit.shared().delegate?.errorKitDidCatch(networkingError: error)
printErrorLog(error)
throw error

} else if let data, data.count > 0 {
do {
// If requested decodable type is Data, received data will be returned.
if V.Type.self == Data.Type.self {
return data as! V
}
let decodableData = try JSONDecoder().decode(V.self, from: data)
return decodableData
} catch let sError {
let error = MBErrorKit.NetworkingError.decodingError(sError, response, data)
MBErrorKit.ErrorKit.shared().delegate?.errorKitDidCatch(serializationError: error)
self.printErrorLog(error)
throw error
}

} else {
let error = MBErrorKit.NetworkingError.unkownError(error, data)
MBErrorKit.ErrorKit.shared().delegate?.errorKitDidCatch(networkingError: error)
printErrorLog(error)
throw error
}
}

private func requestData(_ urlRequest: URLRequest) async -> (URLResponse?, Data?, Error?) {
// TODO: Should async support Session.shared.taskInProgress cancellation logic?
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Rashidium burada şu kodu kullanamaz mıyız abi?

    private func requestData(_ urlRequest: URLRequest) async -> (URLResponse?, Data?, Error?) {
        let taskId = UUID().uuidString
        var task: URLSessionDataTask!

        return await withCheckedContinuation { continuation in
            task = Session.shared.session.dataTask(with: urlRequest) { data, response, error in
                if let error = error {
                    Session.shared.networkLogMonitoringDelegate?.logTask(task: task, didCompleteWithError: error)
                    Session.shared.tasksInProgress.removeValue(forKey: taskId)
                    continuation.resume(returning: (response, data, error))
                    return
                }
                
                if let data, let response {
                    Session.shared.networkLogMonitoringDelegate?.logDataTask(dataTask: task, didReceive: data)
                    Session.shared.networkLogMonitoringDelegate?.logTask(task: task, didCompleteWithError: nil)
                    Session.shared.tasksInProgress.removeValue(forKey: taskId)
                    self.printResponse(data)
                    continuation.resume(returning: (response, data, nil))
                }
            }

            Session.shared.tasksInProgress[taskId] = task
            Session.shared.networkLogMonitoringDelegate?.logTaskCreated(task: task)
            task.resume()
        }
    }

kendim ufak bir uygulama yaptım. Pulse ile dinleyebiliyorum şuan network u

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yapılabilir Eser ama with checked continuation tam olarak async desteği getiriyor mu emin değilim. http://github.com/mobven/binbin-ios 'taki networkü incelemeni tavsiye ederim. eğer test'lerimizi geçerse ordaki yapıyı yeni altyapımız yapacağız.


do {
let (data, response) = try await Session.shared.session.data(for: urlRequest)
printResponse(data)
return (response, data, nil)
} catch {
return (nil, nil, error)
}
}
}
2 changes: 1 addition & 1 deletion Sources/MBNetworking/Networkable+Logs.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ extension Networkable {
}

private func getStringFrom(_ data: Data?) -> String {
if let data = data {
if let data {
if let jsonObject = try? JSONSerialization.jsonObject(with: data, options: .allowFragments),
!(jsonObject is NSNull),
let json = try? JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted),
Expand Down
81 changes: 0 additions & 81 deletions Sources/MBNetworking/Networkable+Pinning.swift

This file was deleted.

Loading