GVKun编程网logo

URL Handle in Swift (一) -- URL 分解(url拆解)

5

想了解URLHandleinSwift(一)--URL分解的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于url拆解的相关问题,此外,我们还将为您介绍关于$str=asdfasdf12354

想了解URL Handle in Swift (一) -- URL 分解的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于url拆解的相关问题,此外,我们还将为您介绍关于$str =asdfasdf123541[url]asdfasdf[/url]cxgew435asdfasdf; [url]asdfasdf[/url] 想把这块去掉,最好的方法是什么。、502 Bad Gateway - Registered endpoint failed to handle the request、Android Handle 主线程向子线程发送数据、Android 模糊搜索rawquery bind or column index out of range: handle 0x2fb180 报错的新知识。

本文目录一览:

URL Handle in Swift (一) -- URL 分解(url拆解)

URL Handle in Swift (一) -- URL 分解(url拆解)

更新时间: 2018-6-6

在程序开发过程之中, 我们总是希望模块化处理某一类相似的事情。 在 ezbuy 开发中, 我接触到了对于 URL 处理的优秀的代码, 学习、改进、记录下来。希望对你有所帮助。

对于 URL 处理, 我将分为两个部分来说明:

  • URL Handle in Swift (一) - URL 分解;
  • URL Handle in Swift (二) - 响应链处理 URL 。

一、 URL 格式分析

URL(Uniform Resource Locator) 全称为“统一资源定位符”, 有时也被俗称为网页地址网址)

URL标准格式如下:

url标准格式

截取《网络是怎样连接的》的图片来解释一下(图侵删)

实际上, URL的标准格式中, 我们可以通过参数来传递相关的信息, 如 https://www.google.com.hk/search?q=rsenjoyer

二、 iOS 客户端处理 URL

iOS客户端的URL大体可以分为两类:

  • 自定义协议的URL, 如: igame://myNote
  • 标准的HTTP(S) URL;

理论上你可以自定义任意的协议来构建URL, 响应协议URL。 在 iOS 开发中,你可以来自定义 URL Scheme 来实现应用程序间的通信。 URL Scheme 相关的信息你可以参考URL Schemes 使用详解 以及 Inter-App Communication。

对于标准的 HTTP(S) URL,不同的URL有着不一样的处理的方式。如:大多情况下, 应用程序受到一个URL就直接用 WKWebView 或者 UIWebView 直接打开; 但处理 Universal Link是需要打开应用程序内对应的页面等。

根据需求, 可以设计出如下的结构图:

不同的URL通过Bridge最终都转换为 “统一”的 Instruction, Instruction保存着 URL所有的信息, “Handler”通过 Instruction的信息执行不一样的处理。

Talk is Cheap, Show me the code!!

2.1 Bridge代码的实现

Bridge 根据URL的不同而转换成 Instruction。

//
//  IGBridge.swift
//  eziNode
//
//  Created by enjoy on 2018/4/9.
//  copyright © 2018年 enjoy. All rights reserved.
//

import Foundation

protocol IGBridge {
    
    func bridgetoIG(from url: URL?) -> IGInstruction?
    
    func bridgetoURL(from instruction: IGInstruction?) -> URL?
}

class IGameAppURLBridge: IGBridge {
    
    private static let iGameAppScheme = "igame"
    
    static let `default` = IGameAppURLBridge()
    
    func bridgetoIG(from url: URL?) -> IGInstruction? {
        
        guard let url = url else { return nil }
        
        guard let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true), urlComponents.scheme?.lowercased() == IGameAppURLBridge.iGameAppScheme else { return nil }
        
        guard let host = urlComponents.host else { return nil }
        
        let queries = makeDictionary(fromQueryItems: urlComponents.queryItems)
        
        let components = urlComponents.path.components(separatedBy: "/").filter { !$0.isEmpty }
        
        let instruction = IGInstruction(type: IGInstructionType(identifier: host), components: components, queryItems: queries, bridge: self)
        
        return instruction
    }
    
    func bridgetoURL(from instruction: IGInstruction?) -> URL? { 
        // 转换为 URL
    }
}

class HttpWebURLBridge: IGBridge {
    // HttpWebURLBridge 的实现
}

class UniversalLinURLBridge: IGBridge {
    // UniversalLinURLBridge 的实现
}

2.2 Instruction代码实现

“Instruction”需要包含着 URL 完整的以及需要怎样被处理. 客户端所支持的 URL 类型实际上可以用一个枚举来列出。


import Foundation

// 客户端支持的URL 类型
public enum IGInstructionType: String {
    
    case specialExercise
    case examinationPaper
    case redoWrong
    case collection
    case myNote
    case refreshQuestionSet
    case unKNown
    
    init(identifier: String?) {
        guard let identifier = identifier else { self = .unKNown;  return }
        
        switch identifier {
        case IGInstructionType.specialExercise.rawValue:
            self = .specialExercise
        case IGInstructionType.examinationPaper.rawValue:
            self = .examinationPaper
        case IGInstructionType.redoWrong.rawValue:
            self = .redoWrong
        case IGInstructionType.collection.rawValue:
            self = .collection
        case IGInstructionType.myNote.rawValue:
            self = .myNote
        case IGInstructionType.refreshQuestionSet.rawValue:
            self = .refreshQuestionSet
        default:
            self = .unKNown
        }
    }
    
}

struct IGInstruction {
    
    let type: IGInstructionType
    
    let components: [String]
    
    var path: String {
        return self.components.isEmpty ? "" : ([""] + self.components).joined(separator: "/")
    }
    
    let queryItems: [String: String]
    
    var bridge: IGBridge?
    
    init(type: IGInstructionType,  components: [String] = [], queryItems: [String: String] = [:], bridge: IGBridge? = nil ) {
        self.type = type
        self.components = components
        self.queryItems = queryItems
        self.bridge = bridge
    }
}

extension IGInstruction {
    
    // Options 下面会提到
    init?(url: URL?, options: IGURLBridgeOptionsInfo = [.iGameApp]) {
        
        if let bridge = options.iGameAppUrlBridge, let ins = bridge.bridgetoIG(from: url) {
            self = ins
            return
        }
        
        if let bridge = options.httpWebUrlBridge, let ins = bridge.bridgetoIG(from: url) {
            self = ins
            return
        }
        
        if let bridge = options.universalUrlBridge, let ins = bridge.bridgetoIG(from: url) {
            self = ins
            return
        }
        
        return nil
    }
}

extension IGInstruction {
    
    var url: URL? {
        return self.bridge?.bridgetoURL(from: self)
    }
}

2.3 Options 可选值

import Foundation

typealias IGURLBridgeOptionsInfo = [IGURLBridgeInfoItem]

enum IGURLBridgeInfoItem {
    
    case iGameApp
    
    case httpWeb
    
    case universalLink
}

precedencegroup ItemComparisonPrecedence {
    associativity: none
    higherThan: LogicalConjunctionPrecedence
}

infix operator <== : ItemComparisonPrecedence

func <== (lhs: IGURLBridgeInfoItem, rhs: IGURLBridgeInfoItem) -> Bool {
    
    switch (lhs, rhs) {
    case (.iGameApp, .iGameApp): return true
    case (.httpWeb, .httpWeb): return true
    case (.universalLink, .universalLink): return true
    default: return false
    }
}

extension Collection where Iterator.Element == IGURLBridgeInfoItem {
    
    func lastMatchIgnoringAssociatedValue(_ target: Iterator.Element) -> Iterator.Element? {
        return reversed().first { $0 <== target }
    }
    
    func removeAllMatchesIgnoringAssociatedValue(_ target: Iterator.Element) -> [Iterator.Element] {
        return filter { !($0 <== target) }
    }
}

extension Collection where Iterator.Element == IGURLBridgeInfoItem {
    
    var iGameAppUrlBridge: IGameAppURLBridge? {
        if let item = lastMatchIgnoringAssociatedValue(.iGameApp),
            case .iGameApp = item
        {
            return IGameAppURLBridge.default
        }
        return nil
    }
    
    var httpWebUrlBridge: HttpWebURLBridge? {
        if let item = lastMatchIgnoringAssociatedValue(.httpWeb),
            case .httpWeb = item
        {
            return HttpWebURLBridge.default
        }
        return nil
    }
    
    var universalUrlBridge: UniversalLinURLBridge? {
        if let item = lastMatchIgnoringAssociatedValue(.universalLink),
            case .universalLink = item
        {
            return UniversalLinURLBridge.default
        }
        return nil
    }
}

AppDelegate实现

iOS AppDelegate 默认是一个全局的单例,因此可以将其设置为处理的入口;

    
    @objc static let current: AppDelegate = UIApplication.shared.delegate as! AppDelegate
    
    @discardableResult
    func handleIGURL(_ url: URL, httpConvertible: Bool = true) -> Bool {
        
        guard let instruction = IGInstruction(url: url, options: httpConvertible ? [.iGameApp, .httpWeb] : [.iGameApp]) else { return false }
        
        return handleIGInstruction(instruction)
    }
    
    func handleIGInstruction(_ ins: IGInstruction) -> Bool {
        
        switch ins.type {
        case .specialExercise, .examinationPaper, .redoWrong, .collection, .myNote, .refreshQuestionSet:
            print("handler --- \(ins.type.rawValue) 类型数据")
        default:
            break
        }
        return true
        
    }
}

$str =asdfasdf123541[url]asdfasdf[/url]cxgew435asdfasdf; [url]asdfasdf[/url] 想把这块去掉,最好的方法是什么。

$str =asdfasdf123541[url]asdfasdf[/url]cxgew435asdfasdf; [url]asdfasdf[/url] 想把这块去掉,最好的方法是什么。

 $str =asdfasdf123541[url]asdfasdf[/url]cxgew435asdfasdf;

[url]asdfasdf[/url]  想把这块去掉,最好的方法是什么。

502 Bad Gateway - Registered endpoint failed to handle the request

502 Bad Gateway - Registered endpoint failed to handle the request

2017-08-07

Greeting from China! I have one question regarding error message “” in SAP cloud platform where I would like to consume an OData service from SAP cloud for customer ( C4C system).

I have a nodejs application where I hard code an end point to an OData service in C4C system. The request is sent to C4C and then I display the result in nodejs console.

The end point for C4C OData service:

https://qxl.dev.sapbydesign.com/sap/byd/odata/v1/opportunity/OpportunityCollection(‘00163E06551B1EE79E9E69D7F8FBCDCF’)

When I test this application locally, it works perfect.

var sURL = "https://qxl-cust233.dev.sapbydesign.com/sap/byd/odata/v1/opportunity/OpportunityCollection(''00163E06551B1EE79E9E69D7F8FBCDCF'')";

  var username = ''WANGJER''
  var password = ''Saptest1''
  var options = {
    url: sURL,
      auth: {
      user: username,
      password: password
    },
    headers: {
      ''Accept'': ''application/json'',
      ''Content-Type'': ''application/json''
    }
  };
  request(options, function (error, response, body) {
    // console.log(''body:'', body); 
    var opportunity = JSON.parse(body);
    var line1 = "Opportunity name: " + opportunity.d.results.Name;
    console.log(line1);
    var line2 = "Responsible: " + opportunity.d.results.MainEmployeeResponsiblePartyName;
    console.log(line2);
    var line3 = "Opportunity id: " + opportunity.d.results.ObjectID;
    console.log(line3);
    var responseText = line1 + "\n" + line2 + "\n" + line3;
    res.send(responseText);
    res.send("another line"); // this line will cause error - repeated send response is not allowed
  }); 

After I upload it to Cloudfoundry@SCP, it fails to work: I set breakpoint in C4C system and found that the request sent from SCP NEVER reaches C4C system. After some times, SCP received error message “502 Bad Gateway - Registered endpoint failed to handle the request”.

要获取更多Jerry的原创文章,请关注公众号"汪子熙":

本文分享 CSDN - 汪子熙。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

Android Handle 主线程向子线程发送数据

Android Handle 主线程向子线程发送数据

 通常情况下,使用 Handler 是子线程向主线程发送数据,今天复习 Handler,思考怎么主线程向子线程发送数据,进过测试没有问题。

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
/**
 * 主线程向子线程发送数据
 * @author gavin
 *
 */
public class MainActivity extends Activity {

    private Handler handler;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //开启子线程
        new connectThread().start();
    }

    public void sendMessage(View v){
        if(handler!=null){
            Message msg =Message.obtain();
            msg.obj ="来着主线程的数据";
            handler.sendMessage(msg);
        }
    }

    //子线程
    class connectThread extends Thread{
        @Override
        public void run() {
            //1.创建Looper对象
            Looper.prepare();
            //2.实例化Handler
            handler =new Handler(){
                public void handleMessage(Message msg) {
                    //接受主线程发送过来的消息
                    super.handleMessage(msg);
                    String info =(String) msg.obj;
                    Log.i("---", info);
                };
            };
            //3.循环读取MessageQueue
            Looper.loop();
        }
    }
}

 

Android 模糊搜索rawquery bind or column index out of range: handle 0x2fb180 报错

Android 模糊搜索rawquery bind or column index out of range: handle 0x2fb180 报错

做模糊搜索时,出现了  bind or column index out of range: handle 0x2fb180 报错
public Cursor getTitle(String word) throws SQLException{
String sql = "select * from contentinfo1 where title =? ";
Cursor cursor = db.rawQuery(sql, new String[] {word});
return cursor;
}


实现精确匹配后,依葫芦画瓢的想制作模糊搜索,套用了SQL语句,不料出错

public Cursor getTitle(String word) throws SQLException{
  String sql = "select * from contentinfo1 where title like ''%"+word+"%''";    
  Cursor cursor = db.rawQuery(sql, new String[]  {word});     
  return cursor;
}

解决方法:
public Cursor getTitle(String word) throws SQLException{
String sql = "select * from contentinfo1 where title like ''%"+word+"%''";
Cursor cursor = db.rawQuery(sql,null);
return cursor;
}

原因:更改语句之后用了+word+而非占位符 ?, 所以rawQuery第二个参数不知道和哪个对应故出现报错
 
进一步修改方案可以参照
http://stackoverflow.com/questions/5716543/android-sqliteexception-bind-or-column-index-out-of-range-problem
需要将第二个rawquery参数更改为NULL

今天关于URL Handle in Swift (一) -- URL 分解url拆解的介绍到此结束,谢谢您的阅读,有关$str =asdfasdf123541[url]asdfasdf[/url]cxgew435asdfasdf; [url]asdfasdf[/url] 想把这块去掉,最好的方法是什么。、502 Bad Gateway - Registered endpoint failed to handle the request、Android Handle 主线程向子线程发送数据、Android 模糊搜索rawquery bind or column index out of range: handle 0x2fb180 报错等更多相关知识的信息可以在本站进行查询。

本文标签: